How to use if-else in Thymeleaf with Spring Boot?

January 04, 2020 No comments Thymeleaf If else Spring Boot

1. Introduction

In this article we will try to answer the question: how to achieve similar to IF - ELSE condition in Thymeleaf.

Check below articles for more information about Thymeleaf if you need it:
Spring Boot with Thymeleaf
Using conditions in Thymeleaf

2. Switch statements

To achieve similar to if-else condition in Thymeleaf we can use th:switch attribute. This command is equivalent to a switch structure in Java. The following example shows how to use it:

<div th:switch="${condition}">
  <p th:case="${true}">TRUE</p>
  <p th:case="*">FALSE</p>
</div>

Thymeleaf at the first step will evaluate ${condition} expression and if the value is true it will print p tag with TRUE text. When an evaluated value is different than true engine will generate p element with FALSE. The default option for th:switch is specified as th:case="*". This simple switch with default handled will work as if-else command.

3. Using th:if and th:unless attributes

Thymeleaf also provides an inverse attribute of th:if which is th:unless. We can use it to construct a conditional sections that work like if-else command.

<div th:if="${condition}">
  <p>TRUE</p>
</div>
<div th:unless="${condition}">
  <p>FALSE</p>
</div>

In this case, we have a little bit more code to provide but on the other hand, it is also much more readable. First div element will be rendered if condition ${condition} evaluates to true and the second div will be shown when condition ${condition} is false.

4. Inline condition

The third way to achieve if-else statement in Thymeleaf is to use a simple inline condition like that shown in the below example:

<div>
    <p th:text="${condition} ? 'TRUE' : 'FALSE'">TRUE or FALSE</p>
</div>

5. Using not before condition

Thymeleaf provides not command that can be used before condition to gives it negation.

<div th:if="${condition}">
  <p>TRUE</p>
</div>
<div th:if="${not condition}">
  <p>FALSE</p>
</div>

6. Conclusion

In this article, we focused on if-else statement in Thymeleaf. We showcased several options to achieve this kind of conditional on the template.

A working version of the code shown in this article is available in our GitHub Repository.

{{ message }}

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