Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf - How to loop a list by index

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})}" 
like image 441
richersoon Avatar asked Jul 14 '16 06:07

richersoon


People also ask

How do you break the loop in Thymeleaf?

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.

How do you pass two objects to a form using Thymeleaf?

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.

What is th block Thymeleaf?

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.


1 Answers

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.

like image 146
Jim Garrison Avatar answered Sep 22 '22 07:09

Jim Garrison