In this quick article, we will look at different ways to check if a certain variable is defined in Thymeleaf templates. Thymeleaf is a popular server-side template engine for Java-based web applications. To learn more about how to use Thymeleaf with Spring Boot, check out this guide.

Using th:if Condition

The simplest way to make sure that a certain variable is defined in Thymeleaf is by using the th:if conditional attribute.

The following example demonstrates how you can display the content of a div tag only if the name variable exists:

<div th:if="${name ne null}">
    Hey there! <span th:text="${name}"></span>
</div>

To check if an attribute of a given object exits, use the following statement:

<div th:if="${user ne null and user.name ne null}">
    Hey there! <span th:text="${user.name}"></span>
</div>

Using Safe Navigation Operator

Another way to check if a specific nullable object exists and it has a property called email, you can make use of safe navigation operator as shown below:

<p>
    Hey there! <span th:text="${user?.email}"></span>
</p>

Using Elvis Operator

Finally, the last method to check if a given variable is defined in Thymeleaf is using the Elvis operator. It is a binary operator that returns if the first expression evaluates to true; otherwise, it returns second expression results.

Here is an example:

<p>
    Hey there! <span th:text="${user.email} ?: '(no email found)'"></span>
</p>

(no email found) will be displayed in the rendered HTML if user.email is empty or null.

Read Next: How to use Thymeleaf with Spring Boot

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.