首页 > 解决方案 > Thymeleaf:如何保持对多重迭代器的计数

问题描述

我想在我的 Thymeleaf 模板中保持对多个迭代器的全局计数。我的带孩子的父母模型如下所示:

val people = listOf(
            Person("p1", listOf(Person("c1"), Person("c2"))),
            Person("p2", listOf(Person("c3"))),
            Person("p3", listOf(Person("c4"), Person("c5"))),
        )

我现在在我的模板中是这样的:

<div>
    <h1>Keep count over multiple iterators</h1>
    <div th:each="parent, parentStat : ${model.data.people}">
        <h2 th:text="${parent.name}"></h2>
        <div th:each="child, childStat : ${parent.children}">
            <span th:text="${child.name}"/> (Global count: <span th:text="${childStat.count}"/>)
        </div>
    </div>
</div>

输出如下所示:

Keep count over multiple iterators
p1
c1 (Global count: 1)
c2 (Global count: 2)
p2
c3 (Global count: 1)
p3
c4 (Global count: 1)
c5 (Global count: 2)

显然,全局计数不起作用,因为它只是当前父级的子级计数。(我只对 1 级父子层次结构感兴趣)。

在 Thymeleaf 中想要我想要的一切可能吗?还是在模型中保持计数的唯一可能性?

标签: thymeleaf

解决方案


我不相信这可以使用 Thymeleaf 来处理。如果您的父母总是保证有相同数量的孩子,那么您可以使用以下方法计算正确的值:

((parent_iteration -1) * children_size) + current_child_count

因此,也许您可​​以使用CSS 计数器

将以下样式添加到您的页面:

body {
    counter-reset: section;                  
}
.countme::before {
    counter-increment: section;
    content: "Child " counter(section) ": ";
}

这包括一个countme类定义——我们可以如下使用它,只要我们还显示一个孩子的名字:

<span class="countme"></span><span th:text="${child.name}"></span>

这会在网页上生成以下输出:

在此处输入图像描述


推荐阅读