How to check if a variable is defined in Thymeleaf

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>

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

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

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:

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

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:

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

(no email found) will be displayed in the rendered HTML if 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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.