Thymeleaf教程(7) - 条件表达式用法
发布于 2022-05-01    449 次阅读
简单的条件:“if” 和“unless” <table> <tr> <th>NAME</th> <th>PRICE</th> <th>IN STOCK</th> <th>COMMENTS</th> </tr> <tr th:each="prod : ${prods}" th:class="${prodStat....

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

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

当${not #lists.isEmpty(prod.comments)}为TRUE的时候。就显示超链接。否则不显示,解析的结果大概是这个样子:

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

th:if不仅判断返回为true的表达式,还判断一些特殊的表达式。

  • 如果值非NULL得话返回true:
    • 如果值是boolean类型并为TURE.
    • 如果值是数值型并不为0.
    • 如果值是字符型并不为空.
    • 如果值是字符型并且内容不为“false”, “off” 或者 “no”。
    • 如果值不是上述类型。
  • 如果值是NULL得话返回false;

th:unless是th:if的反义。

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

如果值都不在上述case里,则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>

版权说明 : 本文为转载文章, 版权为原作者所有

原文标题 : Thymeleaf教程 (七) 条件表达式用法

原文连接 : https://blog.csdn.net/mygzs/article/details/52527480