Basic Iteration with th:each
The th:each attribute is Thymeleaf's way of looping through collections. It works like a for-each loop in Java.
- Item name
For each element in the items collection, Thymeleaf creates a variable called item and renders the element.
Iterating Different Collection Types
th:each works with Lists, Sets, Arrays, and Maps. The syntax stays the same.
User
Tag
Value
When iterating over a Map, each entry gives you access to both the key and value.
Loop Variable Names
You can name your loop variable anything you want. Just make sure it's descriptive.
1
Product Name
0.00
Using meaningful names like product instead of item makes your code much more readable.
Iteration Counter
Thymeleaf provides a status object that gives you useful information about the iteration, like the current index.
0 - Item
The second parameter iterStat is the status object. It starts at 0 by default.
Nested Iterations
You can nest th:each attributes to work with multi-level data structures.
Category
- Product
Nested loops are common when dealing with hierarchical data like categories and products.
Iterating with Index
Sometimes you need the index for styling or logic. Use the status object to get it.
1. Color
The status object has properties like index, count, first, last, even, and odd.