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:
In this example ${customer.name}
will be displayed only if customer
object is not null and customer.name
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}