如何过滤百里香的集合:每个使用另一个属性进行比较

gma*_*oor 6 html spring-mvc spring-el thymeleaf

我试图通过以下url中的示例使用Thymeleaf过滤集合."投影和选择收集"部分. http://doanduyhai.wordpress.com/2012/04/14/spring-mvc-part-iv-thymeleaf-advanced-usage/

<tr th:each="artist,rowStat : ${listArtits.?[alive == true]}">
...
</tr>
Run Code Online (Sandbox Code Playgroud)

但是我想使用另一个属性而不是固定值(true/false).例如

<tr th:each="artist,rowStat : ${listArtits.?[played > playedCountReq]}">
...
</tr>
Run Code Online (Sandbox Code Playgroud)

其中,playingCountReq是Thymeleaf可用的另一种形式变量.我收到以下错误.在类型的对象上找不到属性或字段'playingCountReq'...

我试过多种方法但没有成功.有什么建议?

Iwo*_*ski 9

我成功了:)这是解决方案:

在控制器中:

(...)
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);
(...)
Run Code Online (Sandbox Code Playgroud)

在HTML中:

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

输出:

30
Run Code Online (Sandbox Code Playgroud)

希望这有帮助


小智 6

在选择过滤器中,未限定的属性与被过滤的集合元素相关。但是,变量#root总是被定义为根上下文对象。这是从选择过滤器中引用根级别变量的方式。

<tr th:each="artist,rowStat : ${listArtists.?[played gt #root.playedCountReq]}">
…
</tr>
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅Spring EL 文档中的“ #this 和 #root 变量”部分。