Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf : How to get first element of list without iterating?

foo.messageData is a list. messageData contains name as a string.

In thymeleaf html template, I want to print the value of name property of the first element of messageData.

Something like foo.messageData[0].name:

<span th:text="foo.messageData[0].name"></span>

and

<span th:text="foo.messageData.get(0).name"></span>

is not working.

How to print this data? Is there any particular syntax for this in Thymeleaf?

I am aware that this value can be printed via iterating using th:each; but I do not want these iterations.

like image 952
Vishwajeet Vatharkar Avatar asked Jan 10 '17 10:01

Vishwajeet Vatharkar


3 Answers

Thymeleaf expressions are SpEL. In your case you can use it like below.

<span th:text="${foo.messageData[0].name}"></span>
like image 157
abaghel Avatar answered Nov 13 '22 15:11

abaghel


Thymeleaf integration with Spring uses the Spring Expression Language (SpEL).

This means that all ${..} expressions will be evaluated by the SpEL engine. You may find all details about accessing List elements here.

Consequently this (note the ${..}):

<span th:text="${foo.messageData[0]}"></span> 

will print the first element in the list foo.messageData.

If foo.messageData contains string elements this:

<span th:text="${foo.messageData[0].name}"></span> 

will print nothing because String-s have no name property.

If foo.messageData contains instances of classes like Inventor from the documentation that I linked above then

<span th:text="${foo.messageData[0].name}"></span>

will print the name of the inventor.

like image 29
Lachezar Balev Avatar answered Nov 13 '22 13:11

Lachezar Balev


Generally, you get to the first element in a via the status variable. Ex. I have a list called, well, "list" and I want to get the very first element in "list"; I'm defining a status variable called 'iter':

th:each="{li, iter: ${list}" th:if="{iter.index} == 0"

The above gives access to the first element in list. For more info on status variables, consult Thymeleaf's Getting Started doc

like image 41
Isaac Riley Avatar answered Nov 13 '22 15:11

Isaac Riley