53

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})}"
2
  • 1
    Why do you need to use the index when you can already just iterate over the collection? Jul 14, 2016 at 6:53
  • Eventually, I want to convert the list to comma delimeted string. I would like to check if the item is the last element. So I must loop by index first.
    – richersoon
    Jul 14, 2016 at 6:55

2 Answers 2

128

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.

50

Thymeleaf always declares implicit iteration status variable if we omit it.

<span th:each="task : ${foo.tasks}">
    <span th:text="${taskStat.index} + ': ' + ${task.name}"></span>
</span>

Here, the status variable name is taskStat which is the aggregation of variable task and the suffix Stat.

Then in the loop, we can refer to taskStat.index, taskStat.size, taskStat.count, taskStat.even and taskStat.odd, taskStat.first and taskStat.last.

Source: Tutorial: Using Thymeleaf - 6.2 Keeping iteration status

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.