【问题标题】:Thymeleaf - How to loop a list by indexThymeleaf - 如何按索引循环列表
【发布时间】:2020-10-18 18:12:43
【问题描述】:

如何按索引循环?

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})}"

【问题讨论】:

  • 既然已经可以遍历集合,为什么还需要使用索引?
  • 最后,我想将列表转换为逗号分隔的字符串。我想检查该项目是否是最后一个元素。所以我必须先按索引循环。

标签: java jakarta-ee thymeleaf each


【解决方案1】:

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

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

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

Tutorial: Using Thymeleaf - 6.2 Keeping iteration status

【讨论】:

    【解决方案2】:

    如果我们省略它,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

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 1970-01-01
      • 2014-01-28
      • 2013-01-30
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多