I'm sending a model attribute object(product) from my controller to th:each tag in view page.
If that object contains 3 values like 0,1,3, I can get by using
th:each="var:${product}"
and then
th:text=${var.id}
,
but here I want only 1. How can i get it?.
Can any one please help me to solve this problem?
The only way I found is to build an other object containing those two objects, and pass it. That works well, but I can't create that kind of object, it's nonsense (even if it works). Of course, the objects aren't as simple as Foo and Bar here, otherwise I would have merge those two.
You can use the "th:text=#{variable}" to print a variable in the Thymeleaf.
Thymeleaf expressions use SpEL (Spring Expression Language), so you can use all the features available from SpEL. From the documentation you can see that contents of a collection/array can be accessed using square brackets.
For example, if products
is a collection of objects each with an id
field:
<div th:text="${products[1].id}"></div>
Then the contents of the div
would be the value of id
in the second object. Other elements can be accessed by changing the index between the square brackets.
Here you can do two things,
1) You can use th:if in your div or any other tag. like this.
<div th:if="${var.variable == <YourValue>}"
th:text="${var.variable}"></div>
2) or you can just send that single value form your controller, and then just you can use that here.
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