In this quick article, we will look at different kinds of conditionals available in Thymeleaf. Thymeleaf is a popular server-side template engine widely used by developers for Java-based web applications.

Thymeleaf provides several conditional attributes like th:if, th:unless, and th:switch that can be used to conditionally hide or show parts of your template in the result. To learn more about how to use Thymeleaf with Spring Boot, check out this tutorial.

Before we discuss how conditionals work in Thymeleaf, let us first define a simple model class named User.java that we will use throughout the article:

User.java

public class User implements Serializable {

    private long id;
    private String name;
    private String gender;
    private String active;
    
    // constructor, getters, and setters removed for brevity
}

Simple Conditionals: "if" and "unless"

Sometimes you only want to display a fragment from your template in the result if a certain condition is met. Thymeleaf provides th:if and th:unless conditional attributes to exclude elements based on a provided condition in the rendered document.

For example, imagine you only want to display those users who are active in the user table. In order to do this, you can use th:if attribute to test the condition along with th:each attribute to iterate over list of users as shown below:

<table>
    <caption>List of Users</caption>
    <thead>
    <tr>
        <th>#</th>
        <th>ID</th>
        <th>Name</th>
        <th>Gender</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="user, stats : ${users}" th:if="${user.active}">
        <td th:text="${stats.index + 1}">1</td>
        <td th:text="${user.id}">100</td>
        <td th:text="${user.name}">John Doe</td>
        <td th:text="${user.gender}">M</td>
    </tr>
    </tbody>
</table>

Thymeleaf engine will evaluate the condition th:if="${user.active}"defined on the tr HTML element. When the evaluated value is false (for inactive users), it will skip the tr tag with all its child tags from the result.

The th:if attribute is not just limited to boolean conditions (true/false). In the following table, you can find all scenarios for which the conditional th:if=${value} expression evaluates to boolean true when it is not null:

DescriptionVariableExample
The value is a boolean and is trueboolean status = true;<th:block th:if="${status}"></th:block>
The value is a number and is non-zeroint age = 25;<th:block th:if="${age}"></th:block>
The value is a character and is non-zerochar ch = 'A';<th:block th:if="${ch}"></th:block>
The value is a String and is not "false", "off" or "no"String str = "Java";<th:block th:if="${str}"></th:block>
The value is not a boolean, a number, a character or a StringObject obj = new Object();<th:block th:if="${obj}"></th:block>

If the value is null, it always evaluates to boolean false.

th:unless is a negative counterpart of th:if attribute that can be used instead of adding not statement before conditionals. For example, instead of using th:if=${not user.active}, you can also use th:unless=${user.active} statement.

Let us look at another example that uses both th:if and th:unless attributes to display descriptive user's gender:

<td>
    <th:block th:if="${user.gender eq 'M'}">Male</th:block>
    <th:block th:unless="${user.gender eq 'M'}">Female</th:block>
</td>

Multiple Conditions

Thymeleaf allows you to combine multiple conditions together using and and or operators.

For example to get a list of active users whose name starts with 'john' prefix, you can do the following:

<tr th:each="user, stats : ${users}" th:if="${user.active and #strings.startsWith(user.name, 'john')}">
    <!-- child nodes here -->
</tr>

Similarly to get a list of active users who are either female or are at least 25 years old, use the following condition:

<tr th:each="user, stats : ${users}" th:if="${user.active and (#strings.equals('F') or user.age gt 25)}">
    <!-- child nodes here -->
</tr>

Switch Statements

Thymeleaf also provides a way to display content conditionally using the equivalent of a switch statement in Java: the th:switch and th:case attributes.

The th:switch and th:case attributes are useful when there are more than two outcomes of an expression. These attributes work not only for constant variables like an enum but also for any other data types such as string or number. Here is an example:

<div th:each="user : ${users}">
    <div th:text="${user.name}"></div>
    <div th:switch="${user.gender}">
        <p th:case="'F'">Female</p>
        <p th:case="'M'">Male</p>
        <p th:case="*">Not specified</p>
    </div>
</div>

Note that as soon as one th:case attribute is evaluated as true, every other th:case attribute in the same switch context is evaluated as false. th:case="*" is used to specify the default option in th:switch statement.

Elvis Operator

Elvis operator, usually written as X ?: Y, X or Y or X || Y, is a binary operator that returns its first operand X if that operand evaluates to a true value, and otherwise evaluates and returns its second operand Y.

Here is an example:

<div th:each="user : ${users}">
    <div th:text="${user.gender} ?: '(not specified)'"></div>
</div>

In the example above, when the gender is specified (empty or null), it will display (not specified) instead of empty space.

The Elvis operator is basically a variant of the ternary conditional operator, X ? X : Y, in the sense that the evaluated result returned by the Elvis operator is approximately equivalent to the result of the ternary conditional operator.

Here is an example of ternary conditional operator that renders an arbitrary text depending on a boolean expression:

<div th:text="${user.active} ? 'Active' : 'Suspended'"></div>

Conclusion

In this article, we covered different conditionals provided by the Thymeleaf template engine. We also looked at simplified examples to learn how to use these conditionals in the Thymeleaf templates.

Thymeleaf is a highly flexible and easy to use template engine. It allows us to write a condition in multiple ways just like Java. It is up to you to choose the method you want to use to evaluate a certain condition.

Read Next: How to use Thymeleaf with Spring Boot

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $3) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.