如何在循环中的 Thymeleaf 变量中添加值并在完成循环后显示最终值
How to add values in Thymeleaf variable in the loop and after complete loop display final value
我是产品设计单,我想使用 table 在 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 也没有全局变量的概念。您最接近的是您放置在模型上的属性。
您可以为此使用 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>
(一般风格评论。如果你想做 thymeleaf 的东西,但不想输出任何你应该使用 <th:block />
——而不是放置 <p />
或 <span />
直接在表行中标记。)
我是产品设计单,我想使用 table 在 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 也没有全局变量的概念。您最接近的是您放置在模型上的属性。
您可以为此使用 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>
(一般风格评论。如果你想做 thymeleaf 的东西,但不想输出任何你应该使用 <th:block />
——而不是放置 <p />
或 <span />
直接在表行中标记。)