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.
Thymeleaf expressions are SpEL. In your case you can use it like below.
<span th:text="${foo.messageData[0].name}"></span>
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.
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
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