ChatGPT解决这个技术问题 Extra ChatGPT

如何在 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

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


S
Sae1962

Thymeleaf 与 <c:choose><c:when> 等效:Thymeleaf 2.0 中引入的 th:switchth: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>

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

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


好的,但是..我如何根据客户类型(即匿名或登录)调用 javascript...
请参阅“文本内联”一章,特别是 thymeleaf.org/documentation.html 中“使用 Thymeleaf”教程中的“JavaScript 内联”部分
我该怎么做 th:switch on an iterator.index 值?我想在值<5时做一组情况,如果值>5则切换到默认情况
@DanielFernández:你能帮我解决一下 stackoverflow.com/questions/48499723/… 吗?我无法直接在这个问题上标记你。真的卡住了。
M
Mahozad

我尝试使用此代码来确定客户是登录还是匿名。我确实使用了 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>

这并不能回答 OP 的问题,因为那是为了避免重复复杂的表达式。和其他解决方案一样,这打破了“自然模板”的想法,这是 Thymeleaf 的主要卖点。不知道自己该怎么做,但只是想指出它以防有人有答案。
@Lucky 这给了我一个错误 EL1007E:(pos 0): Property or field 'Status' cannot be found
@Jackie 在上面的示例中,客户是一个对象,匿名是客户类中的一个布尔字段。确保您的对象不为空且字段名称正确。
M
Mahozad

除了 Daniel Fernández,我还想分享我与安全相关的示例。

<div th:switch="${#authentication}? ${#authorization.expression('isAuthenticated()')} : ${false}">
    <span th:case="${false}">User is not logged in</span>
    <span th:case="${true}">Logged in user</span>
    <span th:case="*">Should never happen, but who knows...</span>
</div>

这是混合“身份验证”和“授权”实用程序对象的复杂表达式,它为 thymeleaf 模板代码产生“真/假”结果。

'authentication' 和 'authorization' 实用程序对象来自 thymeleaf extras springsecurity3 library。当 'authentication' 对象不可用或 authorization.expression('isAuthenticated()') 评估为 'false' 时,表达式返回 ${false},否则返回 ${true}。


这是一个很好的提示,但请注意,您可以使用 truefalse 文字——您不需要为它们使用变量替换表达式。另见Yatendra's answer
L
Lucky

您可以使用

If-then-else:  (if) ? (then) : (else)

例子:

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

对于提出相同问题的新人来说,这可能很有用。


M
Mahozad

另一种解决方案 - 您可以使用局部变量:

<div th:with="expr_result = ${potentially_complex_expression}">
    <div th:if="${expr_result}">
        <h2>Hello!</h2>
    </div>
    <div th:unless="${expr_result}">
        <span class="xxx">Something else</span>
    </div>
</div>

有关局部变量的更多信息:
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#local-variables


我认为您在代码中添加了一个额外的“=”符号。如果我是对的,请再次验证并更正。
在我看来,代码没问题。我不知道您指的是哪个额外的“=”符号。
是的,代码没问题。抱歉,我将它与表达式具有 : 而不是 =th:each 混淆了
但是这个答案非常接近我的解决方案。虽然做 th:with 表达对我来说似乎是多余的。基本上这个解决方案使用 th:if 和 th:unless 条件语句。
我认为这不是多余的。如果您只使用 th:if 和 th:unless 复杂表达式将被执行两次...
G
Grigory Kislin

在更简单的情况下(当 html 标签相同时):

<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>

你知道如何在这个表达式中添加“Hello”和“Something else”的翻译吗?
@Laura您可以使用国际化并根据属性文件中的位置加载不同的语言翻译。请参阅looksok.wordpress.com/tag/internationalizationmarcelustrojahn.com/2016/12/…
引用问题:“重要的是我使用了两个不同的 HTML 标签:比如说 h2span。”
v
vphilipnyc

另一种解决方案是使用 not 来获得相反的否定:

<h2 th:if="${potentially_complex_expression}">Hello!</h2>
<span class="xxx" th:if="${not potentially_complex_expression}">Something else</span>

documentation 中所述,它与使用 th:unless 相同。正如其他答案所解释的:

此外,th:if 有一个逆属性 th:unless,我们可以在前面的示例中使用它,而不是在 OGNL 表达式中使用 not

使用 not 也可以,但恕我直言,使用 th:unless 而不是用 not 否定条件更具可读性。


这仍然会重复表达式,这正是 OP 试图避免的事情。
A
Amit

使用 th:switch 作为 if-else

<span th:switch="${isThisTrue}">
  <i th:case="true" class="fas fa-check green-text"></i>
  <i th:case="false" class="fas fa-times red-text"></i>
</span>

使用 th:switch 作为开关

<span th:switch="${fruit}">
  <i th:case="Apple" class="fas fa-check red-text"></i>
  <i th:case="Orange" class="fas fa-times orange-text"></i>
  <i th:case="*" class="fas fa-times yellow-text"></i>
</span>

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


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

T
Tứ Nguyễn Duy
<div style="width:100%">
<span th:each="i : ${#numbers.sequence(1, 3)}">
<span th:if="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-success custom-width" th:text="${i}"></a
</span>
<span th:unless="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-danger custom-width" th:text="${i}"></a> 
</span>
</span>
</div>

enter image description here


D
DuDa

当我想根据用户的性别显示照片时,这对我有用:

<img th:src="${generou}=='Femenino' ? @{/images/user_mujer.jpg}: @{/images/user.jpg}" alt="AdminLTE Logo" class="brand-image img-circle elevation-3">


g
gapserg

If-then-else 有 2 个变体。

第一:
<form method="get" th:action="@{/{id}(id=${user.isAdmin()}?'admin':'user')}"> <input type="submit" value="to Main"/></form>

第二:<th:block th:if!="${branchMessages.isEmpty()}"> ... </th:block> <th:block th:unless="${branchMessages.isEmpty()}"> ... </th:block>