How to do if-else in Thymeleaf?
Thymeleaf has an equivalent to <c:choose>
and <c:when>
: the th:switch
and th:case
attributes introduced in Thymeleaf 2.0.
They work as you'd expect, using *
for the default case:
<div th:switch="${user.role}"> <p th:case="'admin'">User is an administrator</p> <p th:case="#{roles.manager}">User is a manager</p> <p th:case="*">User is some other thing</p> </div>
See this for a quick explanation of syntax (or the Thymeleaf tutorials).
Disclaimer: As required by StackOverflow rules, I'm the author of Thymeleaf.
I tried this code to find out if a customer is logged in or anonymous. I did using the th:if
and th:unless
conditional expressions. Pretty simple way to do it.
<!-- IF CUSTOMER IS ANONYMOUS --><div th:if="${customer.anonymous}"> <div>Welcome, Guest</div></div><!-- ELSE --><div th:unless="${customer.anonymous}"> <div th:text=" 'Hi,' + ${customer.name}">Hi, User</div></div>
I'd like to share my example related to security in addition to Daniel Fernández.
<div th:switch="${#authentication}? ${#authorization.expression('isAuthenticated()')} : ${false}"> <span th:case="${false}">User is not logged in</span> <span th:case="${true}">Logged in user</span> <span th:case="*">Should never happen, but who knows...</span></div>
Here is complex expression with mixed 'authentication' and 'authorization' utility objects which produces 'true/false' result for thymeleaf template code.
The 'authentication' and 'authorization' utility objects came from thymeleaf extras springsecurity3 library.When 'authentication' object is not available OR authorization.expression('isAuthenticated()') evaluates to 'false', expression returns ${false}, otherwise ${true}.