How to do if-else in Thymeleaf?

Maciej Ziarko picture Maciej Ziarko · Nov 21, 2012 · Viewed 290.7k times · Source

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?

Answer

Daniel Fern&#225;ndez picture Daniel Fernández · Nov 28, 2012

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.