列表有 2 个元素 [0]、[1]。
列表中的元素 - [0] 在嵌套 ArrayList 中有五个元素 [0][1]、[2]、[3]、[4]、[5]
[1] 有 4 个元素 [0]、[1]、[2]、[3]、[4]
如何获得 Thymeleaf 中的总长度/大小,即 9?如果可能的话,我需要在任何循环之外使用它来保存临时值。
这让我想到了下一个问题,如何仅使用 .size 而不迭代数据结构来保存 Thymeleaf 中的本地自定义变量?如果需要,我准备编写一个循环来获取此 .size,但我想将其存储在一个局部变量中,稍后我可以在另一个循环中重用该变量!
示例:
<div th:each="test : ${testList}">
<div th:each="testItem : ${test.subArrayList}">
<div th:each="testItemSub : ${testItem}">
<span> Get total size of "${testItemSub.name}" and store in a variable</span>
</div>
</div>
</div>
最佳答案
您可以通过 http://www.thymeleaf.org/doc/usingthymeleaf.html#local-variables 的 th:with
属性设置局部变量。但是,我发现无法在设置后更新元素内的局部变量。换句话说,与 JSP 不同,不能在 View /模板内创建和操作变量。
解决您的特定用例的最简单方法是:
- 设置一个模型对象,其中包含一个方法,该方法将 ArrayList 作为其参数并返回计数。显然,您可以在 Java 代码中实现您需要的任何逻辑。
- 类似地,可以使用 Spring bean 而不是模型对象。使用语法:
${@myBean.doSomething()}
- 类似地,可以使用 Spring bean 而不是模型对象。使用语法:
- 使用 Thymeleaf 附带的
#ids
表达式实用程序对象。如果您使用''
的 id,它可以用作模板内的计数器。然而,只有当整个模板中只有一个这样的计数器时,这才有效。引用:http://www.thymeleaf.org/doc/usingthymeleaf.html#ids
基于原始问题的 #ids
用法示例:
<div th:each="test : ${testList}">
<div th:each="testItem : ${test.subArrayList}">
<div th:each="testItemSub : ${testItem}">
<span> Get total size of "${testItemSub.name}" and store in a variable</span>
<!--/*/ <th:block th:text="${#ids.seq('')}"></th:block> /*/-->
</div>
</div>
</div>
<p>There are a total of <span th:text="${#ids.prev('')}">123</span> elements.</p>
关于Thymeleaf 嵌套列表/ArrayList - 获取所有元素的总大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26152221/