Skip to content

7 条件判断

7.1 简单条件判断:ifunless

在模板开发中,你常会需要让某段模板内容仅在满足特定条件时才渲染

比如这个场景:我们想在产品表格中新增一列,显示每个产品的评论数量;并且如果该产品有评论,就显示一个指向评论详情页的链接。

要实现这个需求,核心就是使用 th:if 属性。

html
<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
    <th>COMMENTS</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    <td>
      <!-- 显示评论数量 -->
      <span th:text="${#lists.size(prod.comments)}">2</span> comment/s
      <!-- 仅当评论列表非空时,渲染评论详情链接 -->
      <a href="comments.html" 
         th:href="@{/product/comments(prodId=${prod.id})}" 
         th:if="${not #lists.isEmpty(prod.comments)}">view</a>
    </td>
  </tr>
</table>

上面的代码太多了,重点关注评论链接的条件渲染代码:

html
<a href="comments.html"
   th:href="@{/product/comments(prodId=${prod.id})}" 
   th:if="${not #lists.isEmpty(prod.comments)}">view</a>

这段代码的作用是: 生成指向 /product/comments 的链接,且携带参数 prodId(值为当前产品 ID);但是仅当产品的评论列表非空 时,才会渲染这个 <a> 标签;若评论为空,标签直接不显示。

让我们看下最终模板处理后的结果:

html
<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
    <th>COMMENTS</th>
  </tr>
  <tr>
    <td>Fresh Sweet Basil</td>
    <td>4.99</td>
    <td>yes</td>
    <td>
      <span>0</span> comment/s <!-- 无评论,无view链接 -->
    </td>
  </tr>
  <tr class="odd">
    <td>Italian Tomato</td>
    <td>1.25</td>
    <td>no</td>
    <td>
      <span>2</span> comment/s
      <a href="/gtvg/product/comments?prodId=2">view</a> <!-- 有评论,显示链接 -->
    </td>
  </tr>
</table>

完美,这正是我们想要的。

注意:th:if 不仅能判断布尔条件,其“真值”判断规则更灵活,具体如下:

变量类型判定为 true 的条件
布尔值(Boolean)值为 true
数字(Number)值非 0(如 1、-2 为 true,0 为 false)
字符(Character)字符编码非 0(即非空字符)
字符串(String)"false""off""no"(如 "yes""123" 为 true,"no" 为 false)
其他对象只要对象非 null(无论是什么类型,比如 List、Map 等)
所有类型值为 null 时,直接判定为 false

th:unlessth:if 的“反义词”,表示“当条件不满足时渲染”。上面的示例也可以用 th:unless 改写,避免表达式中的 not

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

总结

  1. th:if 用于“满足条件则渲染元素”,th:unless 用于“不满足条件则渲染元素”,是模板中最基础的条件判断方式;
  2. th:if 的真值判断规则覆盖布尔、数字、字符串、对象等多种类型,核心是“非 null + 符合类型的真值规则”;
  3. 条件判断常与遍历、链接生成结合(如示例中仅为有评论的产品显示详情链接),是动态模板的核心能力之一。