Thymeleaf Switch Case Example

By Arvind Rai, 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 and th: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> 
Output for the writer.type : Poet
<td>
	<p>He is the Poet</p>
</td> 
Output for the writer.type : Blogger
<td>
	<p>He is the Blogger</p>
</td> 
Output for the 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> 
Output for writer.type : Blogger
<td>
   <p>Blogger</p>
</td> 

3. Using Enum

Suppose we have a following enum.
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;
  }
} 
Set the enum into servlet context.
ctx.setVariable("directions", Direction.values()); 
Find the Thymeleaf code to use switch statement using 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> 
Output for the 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> 

5. Reference

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us