spring 对于 Thymeleaf 中的每个运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36744655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:03:39  来源:igfitidea点击:

For each operator in Thymeleaf

springspring-mvcfor-loopforeachthymeleaf

提问by Andremoniy

I can not find syntax for building simple for-each-loop in Thymeleaftemplate. I'm not satisfied with just th:each=""attribute, because it copies tag in which it's located.

我找不到在Thymeleaf模板中构建简单 for-each-loop 的语法。我对仅th:each=""属性不满意,因为它复制了它所在的标签。

What I'm looking for is something like:

我正在寻找的是这样的:

<th:foreach th:each="...">
...block to be repeated...
</th>

what is analogue of <c:forEach items="..." var="...">or <t:loop source="..." value="...">in Tapestry. Is anything similar for that?

什么是<c:forEach items="..." var="..."><t:loop source="..." value="...">in 的类似物Tapestry。有什么类似的吗?

回答by ekem chitsiga

Use th:blockas stated in the Thymeleaf guide

th:block按照 Thymeleaf 指南中的说明使用

th:blockis a mere attribute container that allows template developers to specify whichever attributes they want. Thymeleaf will execute these attributes and then simply make the block disappear without a trace.

th:block只是一个属性容器,允许模板开发人员指定他们想要的任何属性。Thymeleaf 将执行这些属性,然后简单地使块消失得无影无踪。

So it could be useful, for example, when creating iterated tables that require more than one <tr>for each element:

因此,例如,在创建<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>

回答by Raibaz

The th:blocksolution is definitely the best one, but alternatively you can also try using th:remove="tag"in order to remove the containing tag:

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>

The benefit of this approach is that you can also pass a Thymeleaf expression to th:removein order to only remove the tag conditionally, e.g. if you want only some users to be included in a <tbody>, besides having other interesting uses.

这种方法的好处是你还可以传递一个 Thymeleaf 表达式th:remove,以便仅有条件地删除标签,例如,如果你只希望一些用户包含在 a 中<tbody>,除了有其他有趣的用途。

Hereis the documentation for th:remove.

th:remove.