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:
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.
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:
5. Using not
before condition
Thymeleaf provides not
command that can be used before condition
to gives it negation.
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}