How to check if a variable is defined in Thymeleaf

January 04, 2020 No comments thymeleaf variable

1. Introduction

In this short article, we will present a method to check if a variable is defined in the Thymeleaf template.

2. th:if condition

You can check if given variable exists using th:if condition attribute.

In the following example if variable exists the div tag will be rendered and presenting text: "Yes, given variable exists!"

<div th:if="${variable != null}">
   Yes, given variable exists!

To check if attribute of given object exists use the following structure:

<div th:if="${variable != null && != null}">
   Yes, given exists!.

3. Conclusion

In this article, we showcased a way to check if the variable used in the Thymeleaf template is defined. Like in any other Java-based application to find out if a variable has a value we need to use comparator. To learn more about conditions in Thymeleaf click the link below:

Using conditions in Thymeleaf

{{ message }}

{{ 'Comments are closed.' | trans }}