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?
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?
Share Improve this question edited Apr 23, 2014 at 11:40 Ex-iT 1,4772 gold badges12 silver badges20 bronze badges asked Apr 23, 2014 at 10:01 Prasanth A RPrasanth A R 4,1749 gold badges50 silver badges77 bronze badges1 Answer
Reset to default 5The key would be to use the iteration status mechanism along with the th:if
or th:unless
conditional attributes.
Relevant references are at:
- https://www.thymeleaf/doc/tutorials/2.1/usingthymeleaf.html#keeping-iteration-status
- https://www.thymeleaf/doc/tutorials/2.1/usingthymeleaf.html#simple-conditionals-if-and-unless
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/doc/tutorials/3.0/usingthymeleaf.html