Thymeleaf - How to loop a list by index

99,173

Solution 1

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.

Solution 2

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

Share:
99,173

Related videos on Youtube

richersoon
Author by

richersoon

Updated on January 05, 2020

Comments

  • richersoon
    richersoon over 4 years

    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})}"
    
    • Jim Garrison
      Jim Garrison almost 8 years
      Why do you need to use the index when you can already just iterate over the collection?
    • richersoon
      richersoon almost 8 years
      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.