在 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
。
你能提出一个更好的方法来实现它吗?
原文由 Maciej Ziarko 发布,翻译遵循 CC BY-SA 4.0 许可协议
Thymeleaf has an equivalent to
<c:choose>
and<c:when>
: theth:switch
andth:case
attributes introduced in Thymeleaf 2.0.它们按照您的预期工作,使用
*
作为默认情况:有关语法的快速说明(或 Thymeleaf 教程),请参阅 此 内容。
_免责声明_:根据 StackOverflow 规则的要求,我是 Thymeleaf 的作者。