Thymeleaf - 如何按索引循环列表

Thymeleaf - How to loop a list 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>

我遇到解析错误

org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as each: "${index: #numbers.sequence(0,  ${student.tasks.length})}"

Thymeleaf th:each 允许您声明迭代状态变量

<span th:each="task,iter : ${foo.tasks}">

然后在循环中可以参考iter.indexiter.size.

Tutorial: Using Thymeleaf - 6.2 Keeping iteration status

如果我们省略它,Thymeleaf 总是声明隐式迭代状态变量。

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

这里的状态变量名是taskStat是变量task加上后缀Stat.

的集合

那么在循环中,我们可以参考taskStat.indextaskStat.sizetaskStat.counttaskStat.eventaskStat.oddtaskStat.firsttaskStat.last.

来源:Tutorial: Using Thymeleaf - 6.2 Keeping iteration status