Thymeleaf Switch Case Example
April 16, 2023
On this page, we will learn using Thymeleaf switch case in our Java application. Thymeleaf provides switch statement with same structure as Java switch statement. To use switch statement, Thymeleaf provides following attributes.
th:switch : Switch expression. To resolve variable from context, use ${ } expression.
th:case : Switch case.
th:case="*" : Switch case for default case.
If one
th:case
is evaluated as true, every other th:case
attribute in the same switch context is evaluated as false.
1. Using Switch Case
Find the Thymeleaf switch statement example. Use switch statement attributes as th:switch andth:case
.
<td th:switch="${writer.type}"> <p th:case="'Poet'">He is the Poet</p> <p th:case="'Blogger'">He is the Blogger</p> <p th:case="'Novelist'">He is the Novelist</p> </td>
writer.type
: Poet
<td> <p>He is the Poet</p> </td>
writer.type
: Blogger
<td> <p>He is the Blogger</p> </td>
writer.type
: Novelist
<td> <p>He is the Novelist</p> </td>
2. Default Case
In Thymeleaf switch case, default case is created by th:case="*" expression.<td th:switch="${writer.type}"> <p th:case="'Poet'">He is the Poet</p> <p th:case="*" th:text=${writer.type}>Other</p> </td>
writer.type
: Blogger
<td> <p>Blogger</p> </td>
3. Using Enum
Suppose we have a followingenum
.
public enum Direction { N("N"), E("E"), S("S"), W("W"); private String value; Direction(String value){ this.value = value; } public String getValue(){ return value; } }
ctx.setVariable("directions", Direction.values());
enum
.
<div th:switch="${directions[0].getValue()}"> <p th:case="'E'">East</p> <p th:case="'W'">West</p> <p th:case="'N'">North</p> <p th:case="'S'">South</p> </div>
directions[0].getValue()
:
<div> <p>North</p> </div>
4. With Iteration
In this example, we are using Thymeleaf switch statement with iteration.<body> <div th:each="dir : ${directions}"> <div th:switch="${dir.getValue()}"> <p th:case="'E'">East</p> <p th:case="'W'">West</p> <p th:case="'N'">North</p> <p th:case="'S'">South</p> </div> </div> <table> <tr th:each="writer : ${writers}"> <td th:switch="${writer.type}"> <p th:case="'Poet'">He is the Poet</p> <p th:case="#{myblog.blogger}">He is the Blogger</p> <p th:case="*" th:text=${writer.type}>Other</p> </td> </tr> </table> </body>