Maciej Ziarko
Maciej Ziarko

Reputation: 12084

How to do if-else in Thymeleaf?

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?

Upvotes: 171

Views: 472545

Answers (15)

Pankaj Sharma
Pankaj Sharma

Reputation: 1

How to do if-else in Thymeleaf?

The above problem can be solved by using the th:if and th:unless conditions concept.

Sometimes you will need a fragment of your template to only appear in the result if a certain condition is met.

For example on the navigation panel you want to display the menu options as per the logged in user role.

For instance, Admin user will have different menu option and simple user will have different menu options.

The syntax for this is as below.

<div th:if="${condition}">
   <p>True condition related code.</p>
</div>
<div th:unless="${condition}">
 <p>False condition related code</p>
</div>

More you can explore from this resource.

if you like it please subscribe the channel.

Upvotes: 0

Lawrence E Bosumbe
Lawrence E Bosumbe

Reputation: 582

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>

Upvotes: 0

戴勝台
戴勝台

Reputation: 61

<div th:switch="true"> 
    <div th:case="${condition}=='1'">answer1...</div>
    <div th:case="${condition}=='2'">answer2...</div>
    <div th:case="*">answer3...</div> 
</div>

Upvotes: 6

Italo Or&#233;
Italo Or&#233;

Reputation: 65

This works for me when I wanted to show a photo depending on the gender of the user:

<img th:src="${generou}=='Femenino' ? @{/images/user_mujer.jpg}: @{/images/user.jpg}" alt="AdminLTE Logo" class="brand-image img-circle elevation-3">

Upvotes: 1

gapserg
gapserg

Reputation: 11

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>

Upvotes: 1

Amit
Amit

Reputation: 34735

Use 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>

Use 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>

Upvotes: 12

Daniel Fern&#225;ndez
Daniel Fern&#225;ndez

Reputation: 7455

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.

Upvotes: 262

Tứ Nguyễn Duy
Tứ Nguyễn Duy

Reputation: 41

<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>

enter image description here

Upvotes: 2

Lucky
Lucky

Reputation: 17345

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>

Upvotes: 138

jareks
jareks

Reputation: 662

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

Upvotes: 17

blandger
blandger

Reputation: 818

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}.

Upvotes: 34

Vikki
Vikki

Reputation: 2015

<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>

Upvotes: 2

Pau
Pau

Reputation: 16086

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.

Upvotes: 7

Grigory Kislin
Grigory Kislin

Reputation: 17990

In simpler case (when html tags is the same):

<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>

Upvotes: 13

Jad B.
Jad B.

Reputation: 1483

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.

Upvotes: 24

Related Questions