Maciej Ziarko Maciej Ziarko - 14 days ago 31
Java Question

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

Important thing is that I use 2 different html tags: let's say
h2
and
span
.

Can you suggest a better way to achieve it?

Answer

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 http://www.thymeleaf.org/whatsnew20.html#swit for a quick explanation of syntax (or the thymeleaf tutorials).