【问题标题】:Thymeleaf: How to exclude outer tag when using th:each?Thymeleaf:使用 th:each 时如何排除外部标签?
【发布时间】:2015-09-04 01:10:57
【问题描述】:

Thymeleaf 2.1.4 官方文档演示了for each 的用法如下:

 <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>
    ...
 </tr>

它在每次迭代中生成一个&lt;tr&gt;,非常适合这种情况。但是在我的情况下,我不需要外部标签(这里是&lt;tr&gt;)。


我的用例是递归生成&lt;bookmark&gt;标签,不包含其他标签,&lt;bookmark&gt;标签必须包含name和href属性。

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<body>

<div th:fragment="locationBookmark(location)">
    <bookmark th:each="map : ${location.subMaps}">
        <bookmark th:name="${map.name}"
                  th:href="'#'+${map.id}" th:include=":: locationBookmark(${map})">
        </bookmark>
    </bookmark>
</div>
</body>
</html>

包含方:

<bookmark th:include="bookmark : locationBookmark(${rootLocation})"/>

非常感谢。

【问题讨论】:

  • 你能提供你不想被外部标签关闭的标签样本吗?
  • @PavelUvarov 我的用例已添加,请参阅我的问题。
  • 让我猜猜:你想制作 n 级子标签?我这么认为是因为:书签不是 html 标签,并且因为不建议不关闭带有内容的标签。如果我是对的 - 你应该以递归方式创建和使用一些子模板。我不太擅长在 ThymeLeaf 中说你应该怎么做,但我当然知道这是可能的 - 请仔细查看他们的文档。

标签: java template-engine thymeleaf


【解决方案1】:

即使可以使用th:remove="tag" 来完成,我还是建议您使用th:block

<th:block th:each="map : ${location.subMaps}">
   <bookmark th:name="${map.name}"
        th:href="'#'+${map.id}" th:include=":: locationBookmark(${map})">
    </bookmark>
</th:block>

【讨论】:

  • @Xipo 我将 更正为 .. 希望这对所有 Thymeleaf 版本都是正确的,但由于 XML 是底层......
【解决方案2】:

我想出了如何解决这个问题,很简单,只需在外部标签中添加th:remove="tag"即可。

【讨论】:

    【解决方案3】:

    您可以使用DIV 标记或任何其他HTML 标记进行循环。这不会生成TR 标记。但是要正确呈现表格,您需要在 TR 标签内添加 TD 标签。

    <div th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
        <td th:text="${prod.name}">Onions</td>
        <td th:text="${prod.price}">2.41</td>
    </div>
    

    【讨论】:

    • 我想要的是完全删除标签,而不是更改其名称。
    【解决方案4】:

    这并不是 OP 所要求的,但它可能对某些人有用:

    标签也可以有条件地删除

    <div class="myConditionalOuterDiv" th:remove="${condition}? tag"}> 
        <span> I'm always there </span>
    </div>
    

    这会移除父元素,但将子元素留在原处。

    来源here

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 2018-01-07
      • 2018-05-09
      • 2015-06-17
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多