In this article, we will discuss how to use Enums in Thymeleaf with an example.
Learn Thymeleaf at https://www.javaguides.net/p/thymeleaf-tutorial.html.
Displaying Enums in a Dropdown Menu
Let's first define our Color enum class:
public enum Color {
BLACK, BLUE, RED, YELLOW, GREEN, ORANGE, PURPLE, WHITE
}
Let's use select and option to create a dropdown that uses our Color enum:
<select name="color">
<option th:each="colorOpt : ${T(com.baeldung.thymeleaf.model.Color).values()}"
th:value="${colorOpt}" th:text="${colorOpt}"></option>
</select>
Use Enum in If Statements
We can use a Thymeleaf if statement with our Color enum to conditionally display text:
<div th:if="${tomato.color == T(com.example.thymeleaf.model.Color).RED}">
Tomato color.
</div>
Another option is to use a string comparison:
<div th:if="${tree.color.name() == 'GREEN'}">
Green is for go.
</div>
Use Enum in Switch-Case Statements
In addition to if statements, Thymeleaf supports a switch-case statement.
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.
Related Thymeleaf Tutorials and Examples
- Introducing Thymeleaf | Thymeleaf Template | Thymeleaf Template Engine
- Thymeleaf Example with Spring Boot
- How to Add CSS and JS to Thymeleaf
- Add Bootstrap CSS to Thymeleaf
- How to handle null values in Thymeleaf?
- How to Loop a List by Index in Thymeleaf
- Thymeleaf Array Example - Array Index, Array Iteration
- Thymeleaf Enums Example
- Thymeleaf If Else Condition Example
- Thymeleaf Switch Case Example
Comments
Post a Comment
Leave Comment