Thymeleaf - 如何按索引循环列表

问题描述 投票:0回答:3
java jakarta-ee thymeleaf each
3个回答
129
投票

Thymeleaf

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

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

然后在循环中可以参考

iter.index
iter.size

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


50
投票

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

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

这里,状态变量名称为

taskStat
,是变量
task
和后缀
Stat
的聚合。

然后在循环中,我们可以引用

taskStat.index
taskStat.size
taskStat.count
taskStat.even
taskStat.odd
taskStat.first
taskStat.last

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


0
投票

首先请原谅我糟糕的英语。

请注意,根据我的经验,关于

index
count
值的状态变量 ([1]) 不会跟踪迭代的状态,而是返回当前对象在迭代中的位置。列出您要循环播放的列表。

例如。 您有一个名为

pairs
的列表,其中有 6 对,如下所示

    0: [id=10, fk=2]
    1: [id=20, fk=2]
    2: [id=30, fk=2]
    3: [id=40, fk=1]
    4: [id=50, fk=1]
    5: [id=60, fk=1]

并且您想在具有

fk=1
的人之前打印具有
fk=2
的人(这是一个示例,此处排序并不重要)。

因此,如果您使用

th_each="p:${pairs}"
后跟
th:if="p.id == 1"
,您将获得

    [id=40, fk=1]
    [id=50, fk=1]
    [id=60, fk=1]
    (...)

正如预期的那样。 但是,您对

pStat.index
pStat.count
值有何期望? 我猜

    (0,1)
    (1,2)
    (2,3)

但是(请使用

<pre>([[${pStat.index}]], [[${pStat.count}]])</pre>
进行验证),您将获得

    (3,4)
    (4,5)
    (5,6)

也就是说,这些对在列表中的位置,而不是迭代本身的状态。 这对您来说可能没问题,但请注意,例如,如果您尝试计算循环从一百个对象列表中提取数据的次数(例如每十个值插入一个

<br />
)结果如果列表的顺序与您使用它的顺序不同,可能会让您感到惊讶。

如果是您的情况,获得此结果的一种方法是使用 Collection Selection ([2]) 结合 Thymeleaf 的

#lists.toList()
提取子列表,如下所示
<th:block th:with="sublist=${#pairs.toList(list.?[fk ==1])}">

这样你将获得

    0: [id=40, fk=1]
    1: [id=50, fk=1]
    2: [id=60, fk=1]

您的第一对将有索引

0
和计数
1

也许这是我正在使用的 thymeleaf 当前版本的一个错误,或者在文档中没有明确说明,但这是我盯着几行代码意外行为(以及一些调试)发现的。

Thymeleaf 迭代 [1]:https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#keeping-iteration-status

SpEL 集合选择 [2]:https://docs.spring.io/spring-framework/reference/core/expressions/language-ref/collection-selection.html

© www.soinside.com 2019 - 2024. All rights reserved.