1. Introduction
In this article, we are going to show how to compare the enum constants in Thymeleaf. We will use special T
syntax available in Spring Expression Language (Sp EL) to access a class-level field or method.
If you need more information about how to use conditions in Thymeleaf, follow below links:
Conditions in Thymeleaf
Using Enums in Thymeleaf
Display enums in Thymeleaf
2. Comparing enum
constants
Let's consider we have the following enum
structure that contains days of the week:
package com.frontbackend.thymeleaf.enums.model;
public enum DayOfTheWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY;
}
We can use T()
syntax to get the static fields from enum
object. The following template will render <span>Weekend</span>
tag if the expression under ${day}
will evaluate to SATURDAY
or SUNDAY
:
<span th:if="${day == T(com.frontbackend.thymeleaf.enums.model.DayOfTheWeek).SATURDAY or day == T(com.frontbackend.thymeleaf.enums.model.DayOfTheWeek).SUNDAY}" th:text="Weekend"></span>
The below example shows how to use enum
values in th:switch
-th:case
statements:
<th:block th:switch="${day}">
<span th:case="${T(com.frontbackend.thymeleaf.enums.model.DayOfTheWeek).MONDAY}">work</span>
<span th:case="${T(com.frontbackend.thymeleaf.enums.model.DayOfTheWeek).TUESDAY}">work</span>
<span th:case="${T(com.frontbackend.thymeleaf.enums.model.DayOfTheWeek).WEDNESDAY}">work</span>
<span th:case="${T(com.frontbackend.thymeleaf.enums.model.DayOfTheWeek).THURSDAY}">work</span>
<span th:case="${T(com.frontbackend.thymeleaf.enums.model.DayOfTheWeek).FRIDAY}">work</span>
<span th:case="${T(com.frontbackend.thymeleaf.enums.model.DayOfTheWeek).SATURDAY}">weekend</span>
<span th:case="${T(com.frontbackend.thymeleaf.enums.model.DayOfTheWeek).SUNDAY}">weekend</span>
</th:block>
3. Conclusion
In this short article, we presented the methods to compare enum
constant values in Thymeleaf templates. We used the special T
syntax available in Spring EL. It can be used to retrieve any static field or method from the Java objects.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}