39

How can I check if a variable is defined in Thymeleaf?

Something like this in Javascript:

if (typeof variable !== 'undefined') { }

or this in PHP:

if (isset($var)) { }

Is there an equivalent in Thymeleaf?

Andrea
  • 15,900
  • 18
  • 65
  • 84

4 Answers4

77

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

Keale
  • 3,924
  • 3
  • 29
  • 46
Trynkiewicz Mariusz
  • 2,722
  • 3
  • 21
  • 27
16

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>
Mahozad
  • 18,032
  • 13
  • 118
  • 133
Lay Leangsros
  • 9,156
  • 7
  • 34
  • 39
  • 4
    For objects, it is fine to use the `if` like that. If the `variable` is an `integer` with value `0`, thymeleaf treats it as a `null` and doesn't enter de `if` code. – cavpollo Sep 26 '18 at 17:25
10

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>
1

You can use conditional operators. This will write variable if exists or empty string:

<p th:text="${variable}?:''"></p>
Aleksandar
  • 636
  • 1
  • 7
  • 24