Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add values in Thymeleaf variable in the loop and after complete loop display final value

I am design bill for products, I want to display all products in thymeleaf template using table and at last, out of loop I want to display sum of price of all products in thymeleaf. how can I define global variable and do it?

<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>

I am geeting 0 as output but I want sum of all products price as output.

How to make variable global and solve my problem?

like image 435
Ketan Navadiya Avatar asked Feb 01 '18 06:02

Ketan Navadiya


People also ask

How do you add variables in Thymeleaf?

We can use the th:with attribute to declare local variables in Thymeleaf templates. A local variable in Thymeleaf is only available for evaluation on all children inside the bounds of the HTML tag that declares it.

How do I change the value of a variable in Thymeleaf?

And you can't change that variable in template. Thymeleaf is just presentation layer, you're trying to achieve something which has to be done on application layer (Java code). If you don't want to use HashMap you could use inheritance and extend object Demo.

What is #{} in Thymeleaf?

#{} is used for message (i18n) expressions. Used to retrieve locale-specific messages from external sources.

How do I print values in Thymeleaf?

You can use the "th:text=#{variable}" to print a variable in the Thymeleaf.


1 Answers

In general you can't change a variable once it's been defined with th:with. They just aren't designed to be used that way. Rather, they are simple temporary variables.

Thymeleaf also doesn't have the concept of global variables. The closest you get to that are attributes you've placed on the model.

You can use collection projection for this:

<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>

(General style comments. If you want to do thymeleaf stuff, but don't want to output anything you should be using <th:block /> -- rather than placing <p /> or <span /> tags directly in tables rows.)

like image 176
Metroids Avatar answered Oct 09 '22 10:10

Metroids