javajakarta-eethymeleafeach

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})}"

Solution

  • 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.