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?