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.