欢迎您的访问
专注于分享最有价值的互联网技术干货

七、条件评估

几个T的资料等你来白嫖
双倍快乐
资源帮找!!!

七、条件评估

7.1 简单条件:“if” 和 “unless”

有时,您需要模板的一部分才能仅在满足特定条件的情况下出现在结果中。

例如,假设我们要在产品表中显示一列,其中包含每个产品的 Comment 数量,如果有 Comment,则指向该产品的 Comment 详细信息页面的链接。

为此,我们将使用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 href="comments.html"
   th:href="@{/product/comments(prodId=${prod.id})}" 
   th:if="${not #lists.isEmpty(prod.comments)}">view</a>

这将创建指向 Comment 页面(URL /product/comments)的链接,该链接的prodId参数设置为产品的id,但前提是该产品有任何 Comment。

让我们看一下结果标记:

<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

  • 如果 value 不为 null:
  • 如果 value 是一个布尔值并且是true

    • 如果 value 是一个数字并且非零
    • 如果 value 是一个字符并且非零
    • 如果 value 是一个 String 且不是“ false”,“ off”或“ no”
    • 如果 value 不是布尔值,数字,字符或字符串。
  • (如果 value 为 null,则 th:if 的值为 false)。

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

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

7.2 switch 语句

还有一种方法可以使用 Java 中的* switch *结构的等效条件来有条件地显示内容:th:switch/th: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>
</div>

请注意,一旦一个th:case属性被评估为true,同一切换上下文中的所有其他th:case属性就被评估为false

默认选项指定为th: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>
赞(0) 打赏
版权归原创作者所有,任何形式转载请联系我们:大白菜博客 » 七、条件评估

评论 抢沙发

0 + 5 =
  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏