在Thymeleaf怎么做if-else? [英] How to do if-else in Thymeleaf?
问题描述
在Thymeleaf中做一个简单的if-else的最佳方法是什么?
What's the best way to do a simple if-else in Thymeleaf?
我想在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>
。
我是什么到目前为止:
<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>
我不想评估 potential_complex_expression
两次。这就是我引入局部变量条件
的原因。
I don't want to evaluate potentially_complex_expression
twice. That's why I introduced local variable condition
.
我仍然不喜欢同时使用 th:if =$ {condition}
和 th:除非=$ {condition}
。
Still I don't like using both th:if="${condition}
and th:unless="${condition}"
.
重要的是我使用了2个不同的html标签:假设 h2
和 span
。
Important thing is that I use 2 different html tags: let's say h2
and span
.
你能建议一个更好的方法吗?
Can you suggest a better way to achieve it?
推荐答案
Thymeleaf具有相当于< c:choose>
和< c:when>
: th:切换
和 th:case
Thymeleaf 2.0中引入的属性。
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>
</div>
参见 http://www.thymeleaf.org/whatsnew20.html#swit 快速解释语法(或百里叶教程)。
See http://www.thymeleaf.org/whatsnew20.html#swit for a quick explanation of syntax (or the thymeleaf tutorials).
免责声明,根据StackOverflow规则的要求:我是百里香的作者。
Disclaimer, as required by StackOverflow rules: I'm the author of thymeleaf.
这篇关于在Thymeleaf怎么做if-else?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!