如何在 Thymeleaf 中执行 if-else?

新手上路,请多包涵

在 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 标签:比如说 h2span

你能提出一个更好的方法来实现它吗?

原文由 Maciej Ziarko 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.5k
2 个回答

Thymeleaf has an equivalent to <c:choose> and <c:when> : the th:switch and th:case attributes introduced in Thymeleaf 2.0.

它们按照您的预期工作,使用 * 作为默认情况:

 <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>

有关语法的快速说明(或 Thymeleaf 教程),请参阅 内容。

_免责声明_:根据 StackOverflow 规则的要求,我是 Thymeleaf 的作者。

原文由 Daniel Fernández 发布,翻译遵循 CC BY-SA 4.0 许可协议

我试过这段代码来查明客户是登录的还是匿名的。我确实使用了 th:ifth:unless 条件表达式。很简单的方法来做到这一点。

 <!-- IF CUSTOMER IS ANONYMOUS -->
<div th:if="${customer.anonymous}">
   <div>Welcome, Guest</div>
</div>
<!-- ELSE -->
<div th:unless="${customer.anonymous}">
   <div th:text=" 'Hi,' + ${customer.name}">Hi, User</div>
</div>

原文由 Lucky 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题