【问题标题】:How to filter a collection in thymeleaf th:each using another property in comparison如何过滤 thymeleaf th:each 中的集合,比较使用另一个属性
【发布时间】:2014-10-20 23:06:42
【问题描述】:

我正在尝试按照以下 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>

但是我想使用另一个属性而不是固定值(真/假)。例如

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

其中playedCountReq 是Thymeleaf 可用的另一个表单变量。我收到以下错误。在类型的对象上找不到属性或字段“playedCountReq”...

我尝试了多种方法,但没有成功。有什么建议吗?

【问题讨论】:

  • 到目前为止我发现的唯一解决方法/解决方案是使用 th:block。移动 th:each 到 th:block 和 th:if 到 tr 标签
  • 请为您的整个表格/表格输入代码,以便我们可以看到完整的图片

标签: html spring-mvc thymeleaf spring-el


【解决方案1】:

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

在控制器中:

(...)
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);
(...)

在 html 中:

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

输出:

30

希望有帮助

【讨论】:

    【解决方案2】:

    在选择过滤器中,不合格的属性与被过滤的集合元素相关。但是,变量#root 始终被定义为根上下文对象。这是您可以在选择过滤器中引用根级别变量的方式。

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

    有关详细信息,请参阅 Spring EL 文档中的“The #this and #root variables”部分。

    【讨论】:

      猜你喜欢
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多