thymeleaf(4) - 条件判断

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mytt_10566/article/details/81517335

官方文档:https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#conditional-evaluation

以下是翻译的官方文档,建议自己阅读下文档。

1. 简单条件:if和unless

有时候,我们需要仅仅在满足一定条件才显示代码片段。例如,在产品表格列中,当产品有评论信息的时候添加一个链接用于查看评论详情,这时候我们就可以使用th:if属性。

<table>
  <tr>
    <th>名称</th>
    <th>价格</th>
    <th>现货</th>
    <th>评论</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">洋葱</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? '是' : '否'">是</td>
    <td>
      <span th:text="${#lists.size(prod.comments)}">2</span> 评论
      <a href="comments.html" 
         th:href="@{/product/comments(prodId=${prod.id})}" 
         th:if="${not #lists.isEmpty(prod.comments)}">查看</a>
    </td>
  </tr>
</table>

当产品评论信息不为空时,才会添加<a>标签。

提示:

th:if属性bu不仅判断boolean条件,它的作用不局限于这些,它会根据以下的规则判定指定的表达式为true:

  • 值不为null
    • 值为boolean且是true
    • 值是数字且非0
    • 值是字符且非0
    • 值是字符串且非false、off、no
    • 值不是boolean、数字、字符、字符串
  • 值为null:判断为false

此外,th:if有一个相对应的属性th:unless,我们可以在之前例子中使用,而不是使用OGNL表达式的not:

<a href="comments.html"
   th:href="@{/comments(prodId=${prod.id})}" 
   th:unless="${#lists.isEmpty(prod.comments)}">查看</a>

2. switch语句

我们可以通过switch语句有条件的展示内容,类似于java中的语法:th:switch/th:case属性集

示例:

<div th:switch="${user.role}">
  <p th:case="'admin'">管理员</p>
  <p th:case="${roles.manager}">管理者</p>
</div>

提示:

一旦th:case属性判断为true,那么在同一个switch上下文中的其他th:case将会判断为false。

默认选项应当被指定为:th:case="*"

<div th:switch="${user.role}">
  <p th:case="'admin'">管理员</p>
  <p th:case="${roles.manager}">管理者</p>
  <p th:case="*">未知角色</p>
</div>

猜你喜欢

转载自blog.csdn.net/mytt_10566/article/details/81517335