2015-08-25 121 views
1

我有一个产品对象列表,我想根据一些条件在HTML页面中迭代它。我想这个迭代只为产品,产品类型为“BAR”。我做了如下。Thymeleaf - 迭代基于对象属性的对象列表

<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”产品只有。我怎样才能做到这一点?

回答

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']进行迭代,这是一个包含只与类型(使用#this.bar引用)等于“BAR”的元素的productList滤波版本。

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