I have a product object list and I want to iterate it in HTML page based on some conditions. I want to iterate this only for the products, which product type is 'BAR'. I have done this as follows.
<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>
But now I want product list to iterate only for the first 5 'BAR' products only. How can I achieve this?
You can first use the "SpEl Collection Selection" syntax to filter your productList
to only elements matching the type "BAR". Then you can use the iteration status prodStat
to only display the first 5 elements. Like so:
<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>
In the above you can see the iteration is now performed over foo.productList.?[#this.type eq 'BAR']
, this is a filtered version of productList
containing only the elements with the type (referenced using #this.bar
) equalling 'BAR'.
The number of iterations is then limited using th:if
and the iteration status prodStat
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments