Thymeleaf教程 (七) 条件表达式用法

简单的条件:“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>

重点在这句:html

<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的时候。就显示超连接。不然不显示,解析的结果大概是这个样子:less

<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的表达式,还判断一些特殊的表达式。spa

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

th:unless是th:if的反义。code

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=”*”语句会生效。htm

<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>
相关文章
相关标签/搜索