# How to check if a variable is defined in Thymeleaf

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jan 22, 2020. Topics: Thymeleaf.
Canonical URL: https://attacomsian.com/blog/thymeleaf-check-if-variable-defined

> A quick article to learn how to check if a certain 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](https://attacomsian.com/blog/spring-boot-thymeleaf-example).

## 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](https://attacomsian.com/blog/thymeleaf-conditions) attribute.

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

```markup
<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:

```markup
<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](https://attacomsian.com/blog/thymeleaf-handling-null-values#using-safe-navigation-operator--) as shown below:

```markup
<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](https://attacomsian.com/blog/thymeleaf-conditions#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:

```markup
<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](https://attacomsian.com/blog/spring-boot-thymeleaf-example)
