Thymeleaf - 如何通过索引循环列表

ric*_*oon 31 java each java-ee thymeleaf

我怎样才能按索引循环?

Foo.java

public Foo {
    private List<String> tasks;
    ...
}
Run Code Online (Sandbox Code Playgroud)

的index.html

<p>Tasks:
    <span th:each="${index: #numbers.sequence(0, ${foo.tasks.length})}">
        <span th:text="${foo.tasks[index]}"></span>
    </span>
</p>
Run Code Online (Sandbox Code Playgroud)

我得到了解析错误

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

Jim*_*son 76

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

<span th:each="task,iter : ${foo.tasks}">
Run Code Online (Sandbox Code Playgroud)

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

请参阅教程:使用Thymeleaf - 6.2保持迭代状态.


naX*_*aXa 7

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

<span th:each="task : ${foo.tasks}">
    <span th:text="${taskStat.index} + ': ' + ${task.name}"></span>
</span>
Run Code Online (Sandbox Code Playgroud)

在这里,状态变量名是taskStat变量task和后缀的集合Stat

然后在循环中,我们可以参照taskStat.indextaskStat.sizetaskStat.counttaskStat.eventaskStat.oddtaskStat.firsttaskStat.last

来源:教程:使用Thymeleaf-6.2保持迭代状态