如何在 Thymeleaf 中执行 if-else? [英] How to do if-else in Thymeleaf?

查看:63
本文介绍了如何在 Thymeleaf 中执行 if-else?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Thymeleaf 中执行简单的 if-else 的最佳方法是什么?

我想在 Thymeleaf 中实现与

相同的效果

<c:when test="${potentially_complex_expression}"><h2>你好!</h2></c:when><c:否则><span class="xxx">别的东西</span></c:否则></c:选择>

在 JSTL 中.

到目前为止我的想法:

<h2 th:if="${condition}">你好!</h2><span th:unless="${condition}" class="xxx">别的</span>

我不想对 potentially_complex_expression 求值两次.这就是我引入局部变量condition的原因.我仍然不喜欢同时使用 th:if="${condition}th:unless="${condition}".

重要的是我使用了两个不同的 HTML 标签:比如 h2span.

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

解决方案

Thymeleaf 有一个等价于 :Thymeleaf 2.0 中引入的 th:switchth:case 属性.

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

<p th:case="'admin'">用户是管理员</p><p th:case="#{roles.manager}">用户是经理</p><p th:case="*">用户是别的东西</p>

请参阅this以获取语法的快速说明(或 Thymeleaf 教程).

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

What's the best way to do a simple if-else in 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>

in JSTL.

What I've figured so far:

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

I don't want to evaluate potentially_complex_expression twice. That's why I introduced local variable condition. Still I don't like using both th:if="${condition} and th:unless="${condition}".

An important thing is that I use two different HTML tags: let's say h2 and span.

Can you suggest a better way to achieve it?

解决方案

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>

See this for a quick explanation of syntax (or the Thymeleaf tutorials).

Disclaimer: As required by StackOverflow rules, I'm the author of Thymeleaf.

这篇关于如何在 Thymeleaf 中执行 if-else?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆