Question

How do I set a limit for an each loop in my thymeleaf HTML page?

For example:

<select id="places" onchange="onPlaceChange();">
    <option value="0">Select Place</option>
    <option th:each="p:${places}" th:text="${p.place_Name}" th:value="${p.id}"></option>
</select>

This code loops through items from a database and limit is the length of the list.

Here the list length is 14 and I want to set that limit to 7, how can I do that?

Was it helpful?

Solution

The key would be to use the iteration status mechanism along with the th:if or th:unless conditional attributes.

Relevant references are at:

So in your case, it would look something along the lines of:

<option th:each="p,pStat : ${places}" th:text="${p.place_Name}" th:value="${p.id}" th:unless="${pStat.index > 7}"></option>

Edit: This answer was written for Thymeleaf 2.1 (at the time), but should work with 3.0 in the same or similar manner. See: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top