freemarker中的list排序功能
直接发一段freemarker官方文档的说明上来给大家瞧瞧:
sort
Returns the sequence sorted in ascending order. This will work only if all subvariables are strings, or if all subvariables are numbers, or, since FreeMarker 2.3.1, if all subvariables are date values (date, time, or date+time). If the subvariables are strings, it uses locale (language) specific lexical sorting (which is usually not case sensitive). For example:
<#assign ls = ["whale", "Barbara", "zeppelin", "aardvark", "beetroot"]?sort>
<#list ls as i>${i} </#LIST>
will print (with US locale at least):
aardvark Barbara beetroot whale zeppelin
sort_by Returns the sequence of hashes sorted by the given hash subvariable in ascending order. The rules are the same as with the sort built-in, except that the subvariables of the sequence must be hashes, and you have to give the name of a hash subvariable that will decide the order. For example:
<#assign ls = [
{"name":"whale", "weight":2000},
{"name":"Barbara", "weight":53},
{"name":"zeppelin", "weight":-200},
{"name":"aardvark", "weight":30},
{"name":"beetroot", "weight":0.3}
]>
Order by name:
<#list ls?sort_by("name") as i>
- ${i.name}: ${i.weight}
</#LIST>
Order by weight:
<#list ls?sort_by("weight") as i>
- ${i.name}: ${i.weight}
</#LIST>
will print (with US locale at least) Order by name: – aardvark: 30 – Barbara: 53 – beetroot: 0.3 – whale: 2000 – zeppelin: -200 Order by weight: – zeppelin: -200 – beetroot: 0.3 – aardvark: 30 – Barbara: 53 – whale: 2000 Since FreeMarker 2.3.1, if the subvariable that you want to use for the sorting is on a deeper level (that is, if it is a subvariable of a subvariable and so on), then you can use a sequence as parameter, that specifies the names of the subvariables that lead down to the desired subvariable. For example:
<#assign members = [
{"name": {"first": "Joe", "last": "Smith"}, "age": 40},
{"name": {"first": "Fred", "last": "Crooger"}, "age": 35},
{"name": {"first": "Amanda", "last": "Fox"}, "age": 25}]>
Sorted by name.last:
<#list members?sort_by(['name', 'last']) as m>
- ${m.name.last}, ${m.name.first}: ${m.age} years old
</#LIST>
will print (with US locale at least): Sorted by name.last: – Crooger, Fred: 35 years old – Fox, Amanda: 25 years old – Smith, Joe: 40 years old

