如何在Thymeleaf中使用if-else语句?

170

在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

你能建议更好的方法来实现吗?

14个回答

1
如果-那么-否则有两种变体。
第一种:
<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>

1
这对我很有帮助,当我想根据用户的性别显示照片时:
<img th:src="${generou}=='Femenino' ? @{/images/user_mujer.jpg}: @{/images/user.jpg}" alt="AdminLTE Logo" class="brand-image img-circle elevation-3">

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

输入图像描述


0

如果和除非有时在使用2个分开的代码块时无法提供预期结果。如果和否则也可以通过在第一个块中使用if语句来实现条件1(TRUE),并在第二个块中使用第二个if语句来进行第一条件失败时的替代选择(FALSE)。

希望这能帮到你。

<div th:with="condition=${potentially_complex_expression}" th:remove="tag">
   //True
   <h2 th:if="${if_condition}">Hello!</h2>

   //False
   <h2 th:if="${alternative_for_false}">Something else</h2>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接