What's the best way to do a simple if
- else
in Thymeleaf?
I want to achieve in Thymeleaf the same effect as
<c:choose>
<c:when test="${potentially_complex_expression}">
<h2>Hello!</h2>
</c:when>
<c:otherwise>
<span class="xxx">Something else</span>
</c:otherwise>
</c:choose>
in JSTL.
What I've figured so far:
<div th:with="condition=${potentially_complex_expression}" th:remove="tag">
<h2 th:if="${condition}">Hello!</h2>
<span th:unless="${condition}" class="xxx">Something else</span>
</div>
I don't want to evaluate potentially_complex_expression
twice. That's why I introduced local variable condition
. Still I don't like using both th:if="${condition}
and th:unless="${condition}"
.
An important thing is that I use two different HTML tags: let's say h2
and span
.
Can you suggest a better way to achieve it?
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}.
You can use
If-then-else: (if) ? (then) : (else)
Example:
'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
It could be useful for the new people asking the same question.
Another solution - you can use local variable:
<div th:with="expr_result = ${potentially_complex_expression}">
<div th:if="${expr_result}">
<h2>Hello!</h2>
</div>
<div th:unless="${expr_result}">
<span class="xxx">Something else</span>
</div>
</div>
More about local variables:
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#local-variables
在更简单的情况下(当 html 标签相同时):
<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>
Another solution is just using not
to get the opposite negation:
<h2 th:if="${potentially_complex_expression}">Hello!</h2>
<span class="xxx" th:if="${not potentially_complex_expression}">Something else</span>
As explained in the documentation , it's the same thing as using th:unless
. As other answers have explained:
Also,
th:if
has an inverse attribute,th:unless
, which we could have used in the previous example instead of using a not inside the OGNL expression
Using not
also works, but IMHO it is more readable to use th:unless
instead of negating the condition with not
.
th:switch
as an if-else
<span th:switch="${isThisTrue}">
<i th:case="true" class="fas fa-check green-text"></i>
<i th:case="false" class="fas fa-times red-text"></i>
</span>
th:switch
as a switch
<span th:switch="${fruit}">
<i th:case="Apple" class="fas fa-check red-text"></i>
<i th:case="Orange" class="fas fa-times orange-text"></i>
<i th:case="*" class="fas fa-times yellow-text"></i>
</span>
<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>
<div th:with="condition=${potentially_complex_expression}" th:remove="tag">
<h2 th:if="${condition}">Hello!</h2>
<span th:unless="${condition}" class="xxx">Something else</span>
</div>
<div style="width:100%">
<span th:each="i : ${#numbers.sequence(1, 3)}">
<span th:if="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-success custom-width" th:text="${i}"></a
</span>
<span th:unless="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-danger custom-width" th:text="${i}"></a>
</span>
</span>
</div>
<div th:switch="true">
<div th:case="${condition}=='1'">answer1...</div>
<div th:case="${condition}=='2'">answer2...</div>
<div th:case="*">answer3...</div>
</div>
当我想根据用户的性别显示照片时,这对我有用:
<img th:src="${generou}=='Femenino' ? @{/images/user_mujer.jpg}: @{/images/user.jpg}" alt="AdminLTE Logo" class="brand-image img-circle elevation-3">
If-then-else have 2 variant.
First:
<form method="get" th:action="@{/{id}(id=${user.isAdmin()}?'admin':'user')}"> <input type="submit" value="to Main"/></form>
Second: <th:block th:if!="${branchMessages.isEmpty()}"> ... </th:block> <th:block th:unless="${branchMessages.isEmpty()}"> ... </th:block>
If and unless sometimes fail to provide the expected result when using 2 separated blocks. If and else can also be achieved by using if statement in the first block for condition 1 (TRUE) and the second if statement is the second block for alternative choice when the first condition fails (FALSE).
Hoping that this will help.
<div th:with="condition=${potentially_complex_expression}" th:remove="tag">
//True
<h2 th:if="${if_condition}">Hello!</h2>
//False
<h2 th:if="${alternative_for_false}">Something else</h2>
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.