如何在循环中以及完成循环后在Thymeleaf变量中添加值以显示最终值

Ket*_*iya 3 html spring thymeleaf spring-boot spring-boot-actuator

我是产品设计帐单,我想使用表格在百里香模板中显示所有产品,最后,我想循环显示百里香中所有产品的价格总和。如何定义全局变量并执行此操作?

<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>
Run Code Online (Sandbox Code Playgroud)

我正在接受0输出,但我希望所有产品的价格总和作为输出。

如何使变量全局化并解决我的问题?

Met*_*ids 6

通常,一旦用th:with定义了变量,就无法更改它。他们只是不被设计为那样使用。相反,它们是简单的临时变量。

Thymeleaf也没有全局变量的概念。您最接近的是放置在模型上的属性。

您可以为此使用集合投影

<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>
Run Code Online (Sandbox Code Playgroud)

(常规样式注释。如果您想做百里香,但又不想输出任何您应该使用的东西,<th:block />而不是直接在表行中放置<p /><span />标记。)