Thymeleaf Looping Guide
Looping in Thymeleaf is achieved using the th:each attribute, with the following syntax:
<th:block th:each="item : ${items}">
<!-- 循环体 -->
</th:block>
The th:each attribute is used to specify the collection or array to iterate through, where item represents the current element being iterated and ${items} is the reference to the collection or array being looped through.
In the loop, you can use Thymeleaf’s Expression Language to reference the properties of the item, such as:
<th:block th:each="item : ${items}">
<p th:text="${item.name}"></p>
</th:block>
The code above loops through each element in the collection or array, where each element has a property called ‘name’, and uses the ‘th:text’ attribute to output the value of the ‘name’ property for each element.
In addition to iterating over collections or arrays, Thymeleaf also supports iterating over Maps, with the syntax as follows:
<th:block th:each="entry : ${map}">
<p th:text="${entry.key}"></p>
<p th:text="${entry.value}"></p>
</th:block>
In the above code, a loop iterates through a Map, where entry is an object containing key and value, and the th:text attribute is used to output the key and value of each entry.
Additionally, Thymeleaf also provides some extra loop variables for accessing the current loop state and index, for example:
- index: the current index of the loop, starting from 0.
- Count: the current iteration count, starting from 1.
- size: the size of the collection or array being traversed.
Here is an example of the code:
<th:block th:each="item, index : ${items}">
<p th:text="${index}"></p>
<p th:text="${item}"></p>
</th:block>
In the code above, in addition to the item variable, the index variable is also used to access the current loop index value.
In conclusion, Thymeleaf’s loop functionality uses the th:each attribute to iterate through collections, arrays, or Maps, and combines expression language to reference elements’ properties or values.