Thymeleaf 3.0教程:7 条件判断
7.1 简单条件: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 href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>
这将创建一个指向“comments”页面( /product/comments)的链接,并将prodId参数设置为产品的标识,但前提是产品有任何注释。
让我们来看看结果。
<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属性不仅计算布尔条件。它的能力远远不止于此,它将按照以下规则将指定的表达式评估为真:
If value is not null: If value is a boolean and is true. If value is a number and is non-zero If value is a character and is non-zero If value is a String and is not “false”, “off” or “no” If value is not a boolean, a number, a character or a String. (If value is null, th:if will evaluate to 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,同一switch上下文中的每隔一个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>