我找不到在Thymeleaf
模板中构建简单的for-each循环的语法。
我对仅使用th:each=""
属性不满意,因为它会复制所在标签。
我正在寻找类似以下语法的东西:
<th:foreach th:each="...">
...block to be repeated...
</th>
在Tapestry中,有没有类似于或的模拟器?是否有类似的东西?请注意,保留HTML标签。
我找不到在Thymeleaf
模板中构建简单的for-each循环的语法。
我对仅使用th:each=""
属性不满意,因为它会复制所在标签。
我正在寻找类似以下语法的东西:
<th:foreach th:each="...">
...block to be repeated...
</th>
按照Thymeleaf指南中所述,使用th:block
。
th:block
只是一个属性容器,允许模板开发人员指定任何他们想要的属性。Thymeleaf将执行这些属性,然后简单地使块消失不留痕迹。
例如,当创建需要每个元素多个<tr>
的迭代表格时,它可能会很有用:
<table>
<th:block th:each="user : ${users}">
<tr>
<td th:text="${user.login}">...</td>
<td th:text="${user.name}">...</td>
</tr>
<tr>
<td colspan="2" th:text="${user.address}">...</td>
</tr>
</th:block>
</table>
th:block
解决方案绝对是最好的选择,但您也可以尝试使用 th:remove="tag"
来移除包含标签:
<table>
<tbody th:each="user : ${users}" th:remove="tag">
<tr>
<td th:text="${user.login}">...</td>
<td th:text="${user.name}">...</td>
</tr>
<tr>
<td colspan="2" th:text="${user.address}">...</td>
</tr>
</tbody>
</table>
这种方法的好处是,你还可以传递一个Thymeleaf表达式给th:remove
,以有条件地删除标签,例如:如果你只想在<tbody>
中包含一些用户,则除了具有其他有趣的用途之外。
这里是关于th:remove
的文档。