2015-08-25 120 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限制。