How to check if list is empty using Thymeleaf?

November 01, 2020 No comments Thymeleaf Lists empty QA

1. Problem

In this short Q&A article, we are going to present how to check if the list is empty in Thymeleaf. This is a common task and many developers face this problem when processing collections in templates.

2. Solution

The solution is pretty simple. Fortunately, Thymeleaf comes with special utility class for lists that has several helper methods.

To check if list is empty use #lists.isEmpty(list) utility method.

Use the following snippet to check if list is empty:

<div th:if="${#lists.isEmpty(myList)}">

</div>

In case you need to check if list is NOT EMPTY use:

<div th:unless="${#lists.isEmpty(myList)}">

</div>

or

<div th:if="${not #lists.isEmpty(myList)}">

</div>

If you not familiar with th:unless statement please check list of available condition statements in thymeleaf.

{{ message }}

{{ 'Comments are closed.' | trans }}