Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the second value in list object using thymeleaf?

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?

like image 238
love kumar Avatar asked Sep 03 '15 05:09

love kumar


People also ask

How do you pass two objects to a form using Thymeleaf?

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.

How do I print a value in Thymeleaf?

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


2 Answers

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.

like image 181
Andrew Avatar answered Oct 18 '22 01:10

Andrew


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.

like image 40
Dev Sabby Avatar answered Oct 18 '22 01:10

Dev Sabby