[java] 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?

This question is related to java jsp if-statement jstl thymeleaf

The answer is


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

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


<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


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>

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>

This work 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">


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


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

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to jsp

Difference between request.getSession() and request.getSession(true) A child container failed during start java.util.concurrent.ExecutionException The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path Using if-else in JSP Passing parameters from jsp to Spring Controller method how to fix Cannot call sendRedirect() after the response has been committed? How to include js and CSS in JSP with spring MVC How to create an alert message in jsp page after submit process is complete getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? How to pass the values from one jsp page to another jsp without submit button?

Examples related to if-statement

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA

Examples related to jstl

Iterating through a List Object in JSP How to get a index value from foreach loop in jstl Get value from hashmap based on key to JSTL How to use if, else condition in jsf to display image Selected value for JSP drop down using JSTL Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core" java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config Adding external resources (CSS/JavaScript/images etc) in JSP Sun JSTL taglib declaration fails with "Can not find the tag library descriptor" How to do if-else in Thymeleaf?

Examples related to thymeleaf

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers Setting up a JavaScript variable from Spring model by using Thymeleaf Thymeleaf: how to use conditionals to dynamically add/remove a CSS class How to set thymeleaf th:field value from other variable Using Thymeleaf when the value is null How to avoid the "Circular view path" exception with Spring MVC test Thymeleaf: Concatenation - Could not parse as expression How to do if-else in Thymeleaf?