在Thymeleaf中,如何用最简单的方式实现if
-else
语句?
我想在Thymeleaf中达到与以下代码相同的效果:
<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>
在JSTL中。
到目前为止我所了解的:
<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>
我不想两次评估potentially_complex_expression
,这就是为什么我引入了本地变量condition
。但我不喜欢同时使用th:if="${condition}
和th:unless="${condition}"
。
重要的是,我使用了两个不同的HTML标签:假设是h2
和span
。
你能建议更好的方法来实现吗?
switch
来实现这个呢?你会把第一个case设置为th:case="true"
吗? - GreenGiant