Thymeleaf 教程

简单条件语句:if 和 unless

有时你需要你的模板的一个片段只有在满足某个条件的情况下才会出现在结果中。

例如:假设我们想在我们的产品表中显示一列每个产品存在的评论数量,如果有任何评论,就显示一个链接到该产品的评论详情页。

为了做到这一点,我们将使用 th:if 属性。

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

我们只需要专注于下面行(<a> 标签):

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

如果产品存在评论,上面将创建一个链接到评论页面(URL 为 /product/comments)的 <a> 链接,参数 prodId 设置为产品的 ID。

执行模板渲染,生成的结果如下:

<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
    </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>
  <tr>
    <td>Yellow Bell Pepper</td>
    <td>2.50</td>
    <td>yes</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr class="odd">
    <td>Old Cheddar</td>
    <td>18.75</td>
    <td>yes</td>
    <td>
      <span>1</span> comment/s
      <a href="/gtvg/product/comments?prodId=4">view</a>
    </td>
  </tr>
</table>

请注意,th:if 属性不仅会评估布尔条件,它将按照这些规则把指定的表达式转换为 true。规则如下:

  • 如果值不是 null

    • 如果值是一个布尔值且为 true

    • 如果值是一个数字并且是非零的

    • 如果值是一个字符,并且是非零的

    • 如果值是一个字符串,并且不是 "false"、"off "或 "no"

    • 如果值不是一个布尔值、一个数字、一个字符或一个字符串

  • 如果值是 null,th:if 将评估为 false

另外,Thymeleaf 提供了一个与 th:if 功能相反的属性 th:unless,我们可以在前面的例子中使用这个属性,而不是在 OGNL 表达式中使用一个 not 语法。例如:

<a href="comments.html"
   th:href="@{/comments(prodId=${prod.id})}" 
   th:unless="${#lists.isEmpty(prod.comments)}">view</a>
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号