Thymeleaf Looping Guide: th:each & Methods
Thymeleaf offers various methods for looping through data, below are some commonly used ones:
- By using the th:each directive, you can iterate over a collection and bind each element in the collection to the current iteration variable. For example:
<ul>
<li th:each="item : ${items}" th:text="${item}"></li>
</ul>
- The index variable used with th:each directive can be used to access the current iteration index value in addition to binding elements in a collection. For example:
<ul>
<li th:each="item, index : ${items}" th:text="${index + 1 + '. ' + item}"></li>
</ul>
- The state variable used with th:each directive: You can use the state variable provided by the th:each directive to access current iteration information. For example:
<table>
<tr th:each="user, status : ${users}">
<td th:text="${status.index + 1}"></td>
<td th:text="${user.name}"></td>
<td th:text="${status.current}"></td>
<td th:text="${status.first}"></td>
<td th:text="${status.last}"></td>
</tr>
</table>
- You can wrap the content to be looped with the th:block directive, then use the th:each directive to loop through the content within the th:block. For example:
<th:block th:each="item : ${items}">
<p th:text="${item}"></p>
</th:block>
These are commonly used looping methods in Thymeleaf, and you can choose the appropriate one based on your specific needs for looping through elements.