love kumar
love kumar

Reputation: 131

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?

Upvotes: 10

Views: 31799

Answers (2)

Dev Sabby
Dev Sabby

Reputation: 1427

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.

Upvotes: 1

Andrew
Andrew

Reputation: 1279

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.

Upvotes: 18

Related Questions