Thymeleaf: check if a variable is defined

Yes, you can easily check if given property exists for your document using following code. Note, that you're creating div tag if condition is met:

<div th:if="${variable != null}" th:text="Yes, variable exists!">
   I wonder, if variable exists...
</div>

If you want using variable's field it's worth checking if this field exists as well

<div th:if="${variable != null && variable.name != null}" th:text="${variable.name}">
   I wonder, if variable.name exists...
</div>

Or even shorter, without using if statement

<div th:text="${variable?.name}">
   I wonder, if variable.name exists...
</div>`

But using this statement you will end creating div tag whether variable or variable.name exist

You can learn more about conditionals in thymeleaf here


Short form:

<div th:if="${currentUser}">
    <h3>Name:</h3><h3 th:text="${currentUser.id}"></h3>
    <h3>Name:</h3><h3 th:text="${currentUser.username}"></h3>
</div>

In order to tell whether the context contains a given variable, you can ask the context variable map directly. This lets one determine whether the variable is specified at all, as opposed to the only the cases where it's defined but with a value of null.

Thymeleaf 2

Use the #vars object's containsKey method:

<div th:if="${#vars.containsKey('myVariable')}" th:text="Yes, $myVariable exists!"></div>

Thymeleaf 3

Use the #ctx object's containsVariable method:

<div th:if="${#ctx.containsVariable('myVariable')}" th:text="Yes, $myVariable exists!"></div>