1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.