I am learning about Thymeleaf in Spring, and I am struggling with list fitlering.
The official Tutorial: Using Thymeleaf does not talk about collection filtering and projection, but I found out that Thymeleaf on Spring uses the Spring Expression Language.
This guide states the following:
${collection.?[property == value]}
${collection.![property]}
This is fine if I have a list of objects, for example a list of persons. Then I can perform things like that:
${persons.?[age >= 18]}
selects all persons of at least 18 years${persons.![name]}
selects the name of every personQuestion:
What if I do not have a list of objects (such as a list of persons) but a list of numbers or list of Strings? How can I perform selection (filtering) then? Things like numbers.?[>10]
does not work.
After some more search, I found the answer in the Spring Expression Language documentation.
In 10.5.11 Variables the documentation states the #this
and #root
variables.
The variable #this is always defined and refers to the current evaluation object (against which unqualified references are resolved).
So, assuming I have a list numbers
filled with integers, ${numbers.?[#this >= 10]}
creates a new list that contains all numbers that are at least 10.