How to display all enum values in Thymeleaf

January 04, 2020 No comments Thymeleaf Enums QA

1. Introduction

In this short article, we are going to present how to display all available enum values in Thymeleaf templates.

More useful information about working with enums in Thymeleaf can be found under below link:
Using Enums in Thymeleaf

2. Using T to access Spring beans

T is a special Spring EL syntax for accessing a type and invoking static methods or getting static properties. We can use it to get all the values from our enum object.

Let's start the example with creating a sample enum object:

package com.frontbackend.thymeleaf.enums.model;

import lombok.Getter;

public enum Country {

    SPAIN("Spain"),
    USA("United States of America"),
    UK("United Kingdom");

    @Getter
    private String displayName;

    Country(String displayName) {
        this.displayName = displayName;
    }
}

To display enum values in the dropdown component we will use magic T to access enum and values() method to retrieve items. Additionally to display different text in option tags we use ${country.displayName} expression to display the inner enum field.

<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Spring Boot Thymeleaf Application - Enums</title>
</head>
<body>

<form th:action="@{/selectedCountry}" method="post" th:object="${birthplace}">
    <select name="country" th:field="*{country}">
        <option th:each="country : ${T(com.frontbackend.thymeleaf.enums.model.Country).values()}"
                th:value="${country}" th:text="${country.displayName}"></option>
    </select>

    <input type="submit" value="Submit"/>
</form>

</body>
</html>

The result: Thymeleaf all enum values in dropdown

3. Conclusion

In this article, we showed how to build a dropdown component using enum values in Thymeleaf. Fortunately, Spring comes with special T syntax that can be used to access static methods available on any Java object. We used it in our example to retrieve enum items and put them into dropdown component.

The code used in this article can be found in our GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}