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>
这会创建一条指向评论页的链接(URL是/product/comments
),并把prodId
参数设置到产品id
上,但是只会在产品有任何评论的情况下。
让我们看一看生成的标记:
<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
:
- 如果值不为null:
- 如果值是布尔值,并且为true
- 如果值是数字,并且不为0
- 如果值是字符,并且不为0
- 如果值是字符串,并且不为“false”, “off”或者“no”
- 如果值不是布尔值,数字,字符或者字符串
- (如果值为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>