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?
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.
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.
#{} is used for message (i18n) expressions. Used to retrieve locale-specific messages from external sources.
You can use the "th:text=#{variable}" to print a variable in the Thymeleaf.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With