【问题标题】:Thymeleaf - Iterate Object list based on an object's propertyThymeleaf - 基于对象的属性迭代对象列表
【发布时间】:2015-08-25 10:44:22
【问题描述】:

我有一个产品对象列表,我想根据某些条件在 HTML 页面中对其进行迭代。我只想针对产品类型为“BAR”的产品进行迭代。我已经这样做了。

<th:block th:if="${#strings.isEmpty(foo.destination)}" >
    <div  th:each ="product, prodStat:${foo.productList}" th:if="${product.type eq 'BAR'}" th:with="bar=${product}">                                   
        <div th:text="${bar.cityName}">London</div>                              
    </div>
</th:block>

但现在我希望产品列表仅针对前 5 个“BAR”产品进行迭代。我怎样才能做到这一点?

【问题讨论】:

    标签: spring-mvc thymeleaf


    【解决方案1】:

    您可以首先使用"SpEl Collection Selection" 语法将您的productList 过滤为仅匹配“BAR”类型的元素。然后您可以使用迭代状态prodStat 仅显示前 5 个元素。像这样:

    <th:block th:if="${#strings.isEmpty(foo.destination)}" >
        <div th:each="product, prodStat:${foo.productList.?[#this.type eq 'BAR']}" 
             th:if="${prodStat.index} lt 5" 
             th:with="bar=${product}">                                   
            <div th:text="${bar.cityName}">London</div>                              
        </div>
    </th:block>
    

    在上面您可以看到迭代现在在foo.productList.?[#this.type eq 'BAR'] 上执行,这是productList 的过滤版本,仅包含类型(使用#this.bar 引用)等于“BAR”的元素。

    然后使用th:if 和迭代状态prodStat 限制迭代次数。

    【讨论】:

      猜你喜欢
      • 2015-12-12
      • 2023-03-24
      • 1970-01-01
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      相关资源
      最近更新 更多