Thymeleaf switch statement with multiple cases

Thymeleaf provides a way to display content conditionally using the equivalent of a switch statement in Java: the th:switch and th:case attributes set.

The th:switch and th:case attributes are useful when there are more than two outcomes of an expression. These attributes work not only for constant variables like an enum but also for any other data types such as string or number.

Here is an example:

<div th:switch="${user.role}">
    <p th:case="'admin'">Administrator</p>
    <p th:case="'manager'">Manager</p>
    <p th:case="'user'">User</p>
</div>

Note that as soon as one th:case attribute is evaluated as true, every other th:case attribute in the same switch context is evaluated as false.

th:case="*" is used to specify the default option in th:switch statement:

<div th:switch="${user.role}">
    <p th:case="'admin'">Administrator</p>
    <p th:case="'manager'">Manager</p>
    <p th:case="'user'">User</p>
    <p th:case="*">Other</p>
</div>

Take a look at this article to learn more about how to use Thymeleaf with Spring Boot.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.