How to filter a collection in thymeleaf th:each using another property in comparison

我与影子孤独终老i 提交于 2020-01-12 08:02:43

问题


I am trying to filter the collection using Thymeleaf by following the example in the following url. "Projection & selection on collection" section. http://doanduyhai.wordpress.com/2012/04/14/spring-mvc-part-iv-thymeleaf-advanced-usage/

<tr th:each="artist,rowStat : ${listArtits.?[alive == true]}">
...
</tr>

However I would like to use another property instead of fixed value (true/false). For example

<tr th:each="artist,rowStat : ${listArtits.?[played > playedCountReq]}">
...
</tr>

where as playedCountReq is another form variable available to Thymeleaf. I get the following error. Property or field 'playedCountReq' cannot be found on object of type ...

I tried multiple ways but no success. Any suggestions?


回答1:


I succeded :) Here is solution:

in controller:

(...)
Person p1 = new Person();
p1.setAge(20);
Person p2 = new Person();
p2.setAge(30);
List<Person> list = Lists.newArrayList(p1,p2);
modelMap.addAttribute("list", list);
Integer minAge = 13;
modelMap.addAttribute("minAge", minAge);
(...)

in html:

<table th:with="min=${minAge}">
<tr th:each="person,rowStat : ${list.?[age > __${min}__]}">
<td><span th:text="${person.age}"></span></td>
</tr>
</table>

Output:

30

Hope this help




回答2:


Within the selection filter, unqualified properties are relative to the element of the collection being filtered. But, the variable #root is always defined to be the root context object. This is how you can refer to variables at the root level from within the selection filter.

<tr th:each="artist,rowStat : ${listArtists.?[played gt #root.playedCountReq]}">
…
</tr>

Refer to "The #this and #root variables" section in the Spring EL documentation for more information.



来源:https://stackoverflow.com/questions/26476393/how-to-filter-a-collection-in-thymeleaf-theach-using-another-property-in-compar

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