Java Thymeleaf - 如何按索引循环列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38367339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:14:48  来源:igfitidea点击:

Thymeleaf - How to loop a list by index

javajakarta-eethymeleafeach

提问by richersoon

How can I loop by index?

如何按索引循环?

Foo.java

文件

public Foo {
    private List<String> tasks;
    ...
}

index.html

索引.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})}"

采纳答案by Jim Garrison

Thymeleaf th:eachallows you to declare an iteration status variable

Thymeleafth:each允许你声明一个迭代状态变量

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

Then in the loop you can refer to iter.indexand iter.size.

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

See Tutorial: Using Thymeleaf - 6.2 Keeping iteration status.

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

回答by naXa

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

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

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

Here, the status variable name is taskStatwhich is the aggregation of variable taskand the suffix Stat.

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

Then in the loop, we can refer to taskStat.index, taskStat.size, taskStat.count, taskStat.evenand taskStat.odd, taskStat.firstand taskStat.last.

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

Source: Tutorial: Using Thymeleaf - 6.2 Keeping iteration status

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