thymeleaf中的th:remove用法

时间:2023-03-09 04:08:22
thymeleaf中的th:remove用法

一.删除模板片段使用th:remove属性

th:remove的值如下:

  1.all:删除包含标签和所有的孩子。

  2.body:不包含标记删除,但删除其所有的孩子。

  3.tag:包含标记的删除,但不删除它的孩子。

  4.all-but-first:删除所有包含标签的孩子,除了第一个。

  5.none:什么也不做。这个值是有用的动态评估。

<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:unless="${#lists.isEmpty(prod.comments)}">view</a>
</td>
</tr>
<tr class="odd" th:remove="all">
<td>Blue Lettuce</td>
<td>9.55</td>
<td>no</td>
<td>
<span>0</span> comment/s
</td>
</tr>
<tr th:remove="all">
<td>Mild Cinnamon</td>
<td>1.99</td>
<td>yes</td>
<td>
<span>3</span> comment/s
<a href="comments.html">view</a>
</td>
</tr>
</table>

结果为:

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

最后两行<tr>被删除了。

二.th:remove属性可以采取任何Thymeleaf标准表达式,只要允许它返回一个字符串值(alltagbodyall-but-first or none)。

  这意味着删除可能是有条件的:

<a href="/something" th:remove="${condition}? tag : none">Link text not to be removed</a>

th:remove 把null 等同于 none,所以下面和上面的其实是一样的:

<a href="/something" th:remove="${condition}? tag">Link text not to be removed</a>

因此,如果${condition} is 是false,将返回null,因此没有删除会被执行。