thymeleaf - 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 来处理。如果您的父母总是保证有相同数量的孩子,那么您可以使用以下方法计算正确的值:
((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>
这会在网页上生成以下输出:
推荐阅读
- vue.js - 如何在 vuejs 模板中使用 $refs 获取元素
- flutter - Flutter Listview/Card/Tile with Details 页面
- c# - WPF 与 WindowsFormsHost 拖放
- .net - 从 .NET Core 中的 MVC 视图重定向到 Razor 页面
- python - 如何从 JSON 文件中删除某行:discord.py
- c - SIGALRM 在指定时间后未终止程序
- mongodb - 如何填充外部字段 ID 的 MongoDB 数组?
- c - 如何按照以下代码使用指针进行位操作?
- shell - xmlstarlet 根据每个中其他属性的值选择属性的值
标签迭代 - reactjs - 从 javascript/react 更新 react bootstrap typeahead 中的输入文本