Thymeleaf is a Java-based templates engine to process HTML, XML, JS, CSS or Plain Text files. It comes with many utility objects and methods use to get useful information about variables, aggregate items in collections, joining them, format date and many more. In this article, we will present Thymeleaf utility methods for Lists. If you want to check the implementation of these methods go here.
2. Available utility methods for lists
Lists utilities are usually available under
#lists expression object. This object has several methods that can help us perform common tasks in our expressions.
|Converts to list
|Method converts Arrays or objects that implements Iterable interface or any kind of collection to List.
|Use this method to get the size of a list. This method will automatically check if given parameter is null.
|Check whether list is empty
|Function checks if list given in parameter is either null or empty.
|Check if element is contained in list
|Method checks if list contains one specified element given in the second parameter.
|Check if elements are contained in list
true if all elements are in the specified list.
|Sort a copy of the given list
|The members of the list must implement a comparable interface
|Sort a copy of the given list with comparator
|This sort method required that the comparator will be provided as a second parameter
3. Usage example
We created an
employee model for this example application purpose with simple structure:
Employee position is hold in
enum with the following available values:
Spring controller is used to handler GET requests on
/employees endpoint. We bind two parameters on result
model: a sample list of employees and a comparator used to compare employees by their salary.
Spring Boot application server is used as a web container:
The sample Thymeleaf template has the following structure:
Results presented on http://localhost:8080/employees page looks like the following
In this article, we presented utility methods available in Thymeleaf for Lists. Utils are useful when we want to perform some specific tasks in our variable expressions. For example, if we want to sort collection before showing its items.
As usual the example used in this article can be found in our GitHub repo.