How to show text if the attribute and property exists in Thymeleaf

January 19, 2020 No comments Thymeleaf Text Conditionally QA

1. Introduction

In this short article, we are going to present an easy way to conditionally present a text in Thymeleaf. We will make use of the attribute precedence mechanism, which establishes the order in which they are executed in the tag.

2. Using th:if attribute with th:text

To conditionally show a text we can simple use two Thymeleaf attributes in a single tag and use the fact that the processor associated withth:if has a higher precedence than the one associated with the th:text attribute. So th:if will be evaluated first:

<span th:if="${customer != null && #strings.isEmpty( == false}" th:text="${}">Customer name</span>

In this example ${} will be displayed only if customer object is not null and is not empty.

3. Conclusion

In this short article, we showed how to make use of the attribute precedence mechanism. We used a simple example of showing a text on the rendered page conditionally.

{{ message }}

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