Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf: check if a variable is defined

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?

like image 668
Andrea Avatar asked Feb 28 '15 15:02

Andrea


People also ask

How do you check condition in Thymeleaf?

Using Switch Case Statement - th:switch Attribute To achieve similar to if-else condition in Thymeleaf , we can use th:switch attribute. Thymeleaf at the first step will evaluate ${condition} expression and if the value is true it will print p tag with TRUE text.

How do I check if a variable is null in Thymeleaf?

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.

How do you display a variable value in Thymeleaf?

You can use the "th:text=#{variable}" to print a variable in the Thymeleaf.

How do you declare a variable in Thymeleaf?

Variables ScopeVariables passed to the Model in a controller have a global scope. This means they can be used in every place of our HTML templates. On the other hand, variables defined in the HTML template have a local scope. They can be used only within the range of the element that they were defined in.


2 Answers

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

like image 99
Trynkiewicz Mariusz Avatar answered Oct 06 '22 15:10

Trynkiewicz Mariusz


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>
like image 37
Lay Leangsros Avatar answered Oct 06 '22 16:10

Lay Leangsros