Thymeleaf Switch Case Condition

In this tutorial, we show how to use the switch-case condition in Thymeleaf HTML templates.

Thymeleaf provides the th:switch and th:case attributes perform switch-case condition.

Thymeleaf Switch-Case Condition Example

Create User Model

package net.javaguides.thymeleaf.model;

public class User {
    private String name;
    private String email;
    private String role;
    private String gender;

    public User(String name, String email, String role, String gender) {
        this.name = name;
        this.email = email;
        this.role = role;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

Create Spring MVC Controller - UserController

Within DemoController class, let's create a handler method to return the view and model:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import net.javaguides.thymeleaf.model.User;

@Controller
public class UserController {

    @GetMapping("switch-case")
    public String user(Model model){
        User user = new User("ramesh","ramesh@gmail.com", "ADMIN", "M");
        model.addAttribute("user", user);
        return "switch-case";
    }
}

Create Thymeleaf template - switch-case.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="ISO-8859-1">
    <title>Thymeleaf switch case Demo</title>

    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet" />
</head>

<body>
<div class="container">
    <div class="row">
        <h1>Thymeleaf switch case demo</h1>
        <h4 th:utext="${user.name}"></h4>
        <div th:switch="${user.role}">
            <p th:case="'ADMIN'">User is an administrator</p>
            <!-- * for default case -->
            <p th:case="*">User is some other thing</p>
        </div>
    </div>

</div>
</body>

</html>
The th:case = "*" is the default case of the th:swith/th:case structure. If all the above cases are evaluated as false then the default case will be "rendered".

Demo:


If the User role is "Admin" then "User is an administrator" text prints on the web page.

Comments