How can I loop by index?
Foo.java
public Foo { private List<String> tasks; ... }
index.html
<p>Tasks: <span th:each="${index: #numbers.sequence(0, ${foo.tasks.length})}"> <span th:text="${foo.tasks[index]}"></span> </span> </p>
I got parse error
org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as each: "${index: #numbers.sequence(0, ${student.tasks.length})}"
The best solution would be the put this logic in the controller and put the first product of type 'T' in a separate attribute. If that's not possible, another solution would be to write a Thymeleaf extension (or if using Spring a bean) that does this.
The only way I found is to build an other object containing those two objects, and pass it. That works well, but I can't create that kind of object, it's nonsense (even if it works). Of course, the objects aren't as simple as Foo and Bar here, otherwise I would have merge those two.
th:block is a Thymeleaf element rather than an attribute, and it has the general syntax: 1 2 3. <th:block> <!-- Your HTML code --> </th:block> th:block allows you to apply the same Thymeleaf attribute, like th:if or th:each to a block of code.
Thymeleaf th:each
allows you to declare an iteration status variable
<span th:each="task,iter : ${foo.tasks}">
Then in the loop you can refer to iter.index
and iter.size
.
See Tutorial: Using Thymeleaf - 6.2 Keeping iteration status.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With