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})}"
naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
richersoon
  • 4,682
  • 13
  • 44
  • 74
  • 1
    Why do you need to use the index when you can already just iterate over the collection? – Jim Garrison Jul 14 '16 at 06: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 '16 at 06:55

2 Answers2

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.

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
49

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

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259