我正在设计产品账单,我想使用表格在 thymeleaf 模板中显示所有产品,最后,在循环外我想显示 thymeleaf 中所有产品的价格总和。我如何定义全局变量并执行它?
<table th:with="totalPrice=0">
<tr th:each="count,iterator: ${product.paidService}">
<td th:text="${iterator.index+1}"></td>
<td th:text="${count.name}"></td>
<td>Paid</td>
<td th:text="${count.price}"></td>
<p th:with="totalPrice=${totalPrice + count.price}"> </p>
</tr>
<span th:text="${totalPrice}"></span>
</table>
我正在接受0
作为输出,但我想要所有产品价格的总和作为输出。
如何使变量全局并解决我的问题?
一般来说,一旦用 th:with 定义了变量,就不能更改它。它们只是不是被设计成这样使用的。相反,它们是简单的临时变量。
Thymeleaf 也没有全局变量的概念。最接近的是您放置在模型上的属性。
您可以使用集合投影 https://docs.spring.io/spring/docs/5.0.3.RELEASE/spring-framework-reference/core.html#expressions-collection-projection为了这:
<table>
<tr th:each="count,iterator: ${product.paidService}">
<td th:text="${iterator.index+1}" />
<td th:text="${count.name}" />
<td>Paid</td>
<td th:text="${count.price}" />
</tr>
<tr>
<td colspan="3" />
<td><b th:text="${#aggregates.sum(product.paidService.![price])}" /></td>
</tr>
</table>
(一般风格注释。如果你想做百里香的东西,但不想输出任何你应该使用的东西<th:block />
——而不是放置<p />
or <span />
直接在表行中标记。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)