if-else在 Thymeleaf中实现表达式的最佳方法是什么?
我想在 Thymeleaf 中实现与我在下面的 JSTL 示例中所做的相同的事情。
使用 JSTL 的示例:
<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>
到目前为止,我在 Thymeleaf 所做的事情:
<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- 这很重要!
有没有更好的方法来做同样的事情?
Thymeleaf 有类似物
<c:choose>和<c:when>:这些是属性
th:switch并th:case在 Thymeleaf 2.0 中引入。例子:
这种结构的工作方式类似于
switchJava 中的类似表达式。中指定的表达式被
th:switch评估并与里面的计算结果进行比较。th:case在这种情况下,该属性
th:case="*"标记了默认情况下应该选择的案例(如果没有其他案例匹配)。您可以在此处(或在Thymeleaf 教程)中了解有关此语法的更多信息。
链接:
th:switchThymeleaf 变更日志中的语法描述https://www.thymeleaf.org/whatsnew20.html#swit
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#switch-statements