🏠Spring BootComparators and equality in Thymeleaf

Comparators and equality in Thymeleaf

Even though we do not pay attention to these operations much, Comparators and equality operators are the key aspects in thymeleaf expressions. In this post, we will see how these operators can be used.

Comparison Operators (Comparators)

You can compare values and expressions using the ><>= and <= Comparators. These operators behave the same way as they would behave in most of the programming languages.

<button th:if="${cart.total} > 0">Checkout</button>Code language: HTML, XML (xml)

You can also use the operators within the expressions. However, they will now get evaluated by SpEL or ONGL.

<button th:if="${cart.total > 0}">Checkout</button>Code language: HTML, XML (xml)

Note that XML and XHTML don’t allow > and < to be placed inside attributes. In these cases, you can either use HTML entities, or their text equivalents such as lt (<),gt (>),le (<=),ge (>=). With that in mind, the below will result in similar output.

<button th:if="${cart.total &gt; 0}">Checkout</button>
<button th:if="${cart.total gt 0}">Checkout</button>Code language: HTML, XML (xml)

Comparators for objects

The Comparators in thymeleaf are not only for primitive data types. You can even compare String objects in thymeleaf.

<button th:if="'Hello' < 'Howdy'">This will be displayed</button>
<button th:if="'Hello' > 'Howdy'">This will not be displayed</button>Code language: HTML, XML (xml)

Under the hood, Thymeleaf uses the String.compareTo() method from the Comparable interface. That is, You can compare any two objects of the same type if they are Comparable.

<button th:if="${father} > ${son}">This is possible</button>Code language: HTML, XML (xml)

If the objects don’t implement Comparable, then you will get the following error or similar.

org.thymeleaf.exceptions.TemplateProcessingException: Cannot execute GREATER THAN from Expression ”${father} > ${son}” .

This exception is due to how thymeleaf comparison operators work.

Equality Operators

Sometimes the expressions may need to evaluate variables and values for equality and inequality. These operations are == and !=. The following are the examples.

<!--  Examples for equality  -->
<a th:if="${role} == 'ADMIN'">Admin Console</a>
<a th:if="${role} eq 'ADMIN'">Admin Console</a>
<!--  Examples for inequality  -->
<a th:if="${status} != 'LOGGEDIN'">Login</a>
<a th:if="${status} ne 'LOGGEDIN'">Login</a>
<a th:if="${status} neq 'LOGGEDIN'">Login</a>Code language: HTML, XML (xml)

As you see in the above example, equality operators also have text aliases as eq (==)neq/ne (!=).

Conclusion

To conclude, We learned about equality and comparators in thymeleaf with few examples. If you want to see them in action, Checkout the thymeleaf CRUD example.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *