Thymeleaf Enums Example

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

  1. Introducing Thymeleaf | Thymeleaf Template | Thymeleaf Template Engine
  2. Thymeleaf Example with Spring Boot
  3. How to Add CSS and JS to Thymeleaf
  4. Add Bootstrap CSS to Thymeleaf
  5. How to handle null values in Thymeleaf?
  6. How to Loop a List by Index in Thymeleaf
  7. Thymeleaf Array Example - Array Index, Array Iteration
  8. Thymeleaf Enums Example
  9. Thymeleaf If Else Condition Example
  10. Thymeleaf Switch Case Example

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments