Iteration
Im Javacode kann gleich eine ganze Collection als Variable mitgegeben werden:
ctx.setVariable("prods", allProducts);
Im HTML-Code kann dann folgendermassen durch eine Collection geloopt werden
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
(Funktioniert mit allen java.util.Iterable)
Beim loopen können dank status-Variabeln auch noch weitere Informationen ausgelesen werden:
- The current iteration index, starting with 0. This is the index property.
- The current iteration index, starting with 1. This is the count property.
- The total amount of elements in the iterated variable. This is the size property.
- The iter variable for each iteration. This is the current property.
- Whether the current iteration is even or odd. These are the even/odd boolean properties.
- Whether the current iteration is the first one. This is the first boolean property.
- Whether the current iteration is the last one. This is the last boolean property.
Hier ein Beispiel:
<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
If you don’t explicitly set a status variable, Thymeleaf will always create one for you by suffixing Stat to the name of the iteration variable:
Das wäre dann zum Beispiel
<tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">