In this article, we will discuss how to use Enums in a switch-case statement of Thymeleaf HTML template with an example.
Use Enum in Switch-Case Statements
Let's consider we have the following enum structure that contains days of the week:
public enum DayOfTheWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY;
}
The below example shows how to use enum values in th:switch and th:case statements:
<th:block th:switch="${day}">
<span th:case="${T(com.example.thymeleaf.enums.model.DayOfTheWeek).MONDAY}">weekday</span>
<span th:case="${T(com.example.thymeleaf.enums.model.DayOfTheWeek).TUESDAY}">weekday</span>
<span th:case="${T(com.example.thymeleaf.enums.model.DayOfTheWeek).WEDNESDAY}">weekday</span>
<span th:case="${T(com.example.thymeleaf.enums.model.DayOfTheWeek).THURSDAY}">weekday</span>
<span th:case="${T(com.example.thymeleaf.enums.model.DayOfTheWeek).FRIDAY}">weekday</span>
<span th:case="${T(com.example.thymeleaf.enums.model.DayOfTheWeek).SATURDAY}">weekend</span>
<span th:case="${T(com.example.thymeleaf.enums.model.DayOfTheWeek).SUNDAY}">weekend</span>
</th:block>
We are using use T() syntax to get the static fields from enum object.
Comments
Post a Comment