How can I sort a list in Play Framework templates?

2019-07-15 10:42发布

问题:

I have this template rendering JSON content:

[
#{list data}
{
    "title": ${_.title},
     "id": ${_.id}
} 
#{if !_isLast},#{/if}#{/list}
]

Is there a way to sort data inside the template before printing the data members?

回答1:

It is possible:

//src
%{
    exampleList = ["z", "y", "a", "b"]
}%

<ul>
#{list items:exampleList.sort(), as:'product'}
    <li>${product}</li>
#{/list}
</ul>
//rendered
<ul>
    <li>a</li>
    <li>b</li>
    <li>y</li>
    <li>z</li>
</ul>

In addition you can give sort() a lambda expression how to sort, some examples are here: http://groovy.codehaus.org/JN1015-Collections

But it is best not to use the template engine at all to render JSON. You can use Jackson from your controller http://wiki.fasterxml.com/JacksonInFiveMinutes or use renderJson from a controller class: http://www.playframework.org/documentation/api/1.2.5/play/mvc/Controller.html . Palako gave you already the hint to sort in the controller.



回答2:

Doing logic such as sorting is what controllers are for, you shouldn't be sorting in your template, templates are for rendering.

Write a Comparator that sorts your json objects following your desired criteria and call Collections.sort(data, yourComparator) before passing data to the template.