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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)