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