如何检查 Thymeleaf 片段是否已定义

2024-01-03

使用时如何检查 Thymeleaf 片段是否已定义“模板装饰代替包含”技术 https://stackoverflow.com/questions/18896915/thymeleaf-templates-is-there-a-way-to-decorate-a-template-instead-of-including?

在下面的例子中模板.html我只希望在定义片段时呈现脚本标签

<html th:fragment="page" xmlns:th="...">
  ...
  <div class="container" th:include="this :: content"></div>
  <script th:include="this :: script"></script>
  ...
</html>

但在我这里索引.html它使用上面的模板,没有定义脚本片段,但脚本标签仍然会呈现

<html th:include="template :: page">
  ...
  <div th:fragment="content">
    ...
  </div>
</html>

我试过了th:if="#{this :: script}"但没有运气


我用 Thymeleaf 玩了一下(...),这是我的结论。

下面我将使用tag对于任何给定的标签(div, script, span等)和fragment可接受的片段语法(this :: script, this :: content, template :: #menu, etc.)

当你使用<tag th:include="fragment"/>,Thymeleaf 总是生成一个<tag>...</tag>。如果不存在,则内容为空<tag></tag>。如果片段存在,则内容成为片段的内容。例如使用<div th:"other :: #foo/>对于一个片段<p id="foo">bar</p> gives <div>bar</div>

当你使用<tag th:replace="fragment"/>,Thymeleaf 尝试用完整的片段(包括标签)替换它。有以下特殊情况:

  • 如果片段不存在,Thymeleaf 不会插入任何内容
  • 如果片段由 a 标识th:fragment="id", Thymeleaf 去除th:fragment (ex: <p th:fragment="foo">bar</p> gives <p>bar</p>, 任何tag is).
  • 如果片段由 dom 元素标识,Thymeleaf 会保留 dom 元素(例如:<p id="foo">bar</p> gives <p id="foo">bar</p>, 任何tag is)

所以,如果你想包括<script>仅当片段存在时,您只需通过以下方式识别它<script th:fragment ...>...</script>当它存在时并将其包含在您的布局中:

<script th:replace="this :: script"/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何检查 Thymeleaf 片段是否已定义 的相关文章

随机推荐