Maciej Ziarko Maciej Ziarko - 1 year ago 744
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:when test="${potentially_complex_expression}">
<span class="xxx">Something else</span>

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>

I don't want to evaluate
twice. That's why I introduced local variable

Still I don't like using both

Important thing is that I use 2 different html tags: let's say

Can you suggest a better way to achieve it?

Answer Source

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> 

See for a quick explanation of syntax (or the thymeleaf tutorials).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download