How can I sort a list in Play Framework templates?

混江龙づ霸主 提交于 2019-12-10 23:54:46

问题


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.



来源:https://stackoverflow.com/questions/13863556/how-can-i-sort-a-list-in-play-framework-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!