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>
相關文章
相關標籤/搜索