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

4

14

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.

Nullity answered 10/1, 2017 at 10:55 Comment(1)
Why don't you put the first element into the model in a separate attribute inside your spring controller, I also think this will make the UI easier to read (unless you need the first element of many different collections)Angelita
D
16

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

<span th:text="${foo.messageData[0].name}"></span>
Delk answered 10/1, 2017 at 11:35 Comment(2)
This syntax does not seem to work. Showing template parsing error.Nullity
Working fine for me. Can you please check the error details.Delk
F
7

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.

Fogarty answered 10/1, 2017 at 11:39 Comment(1)
Apparently I had a syntax error, and I was using "${..}" but was missing the last " Anyway, thanks for help! :-) I feel like I should delete the question.Nullity
R
1

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

Ruching answered 4/9, 2018 at 0:34 Comment(0)
K
0

<h1 th:with="firstUse=${uses[0]}" th:text="${firstUse.categoryId}"></h1> This worked for me,
https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#local-variables https://www.baeldung.com/thymeleaf-variables#define-variables

Kristoforo answered 23/11, 2022 at 22:22 Comment(1)
Please elaborate your codeJitterbug

© 2022 - 2024 — McMap. All rights reserved.