【问题标题】:How to check Thymeleaf fragment is defined如何检查 Thymeleaf 片段已定义
【发布时间】:2014-08-25 19:56:47
【问题描述】:

使用"template decoration instead of inclusion" technique时如何检查Thymeleaf片段是否定义?

在下面的 template.html 示例中,我只希望在定义片段时呈现脚本标记

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

但是在我的 index.html 中,它使用了上面的模板,没有定义脚本片段,但脚本标签仍然会呈现

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

我试过th:if="#{this :: script}",但没有成功

【问题讨论】:

  • 你试过th:replace而不是th:include吗?

标签: java spring thymeleaf


【解决方案1】:

我和 Thymeleaf 玩了一点(...),这是我的结论。

在下文中,我将对任何给定标签(divscriptspan 等)使用tagfragment 可接受的片段语法(this :: scriptthis :: contenttemplate :: #menu等)

当您使用&lt;tag th:include="fragment"/&gt; 时,Thymeleaf 总是会生成一个&lt;tag&gt;...&lt;/tag&gt;。如果不存在,则内容为空,给出&lt;tag&gt;&lt;/tag&gt;。如果片段存在,则内容成为片段的内容。例如使用&lt;div th:"other :: #foo/&gt; 片段&lt;p id="foo"&gt;bar&lt;/p&gt; 给出&lt;div&gt;bar&lt;/div&gt;

当您使用&lt;tag th:replace="fragment"/&gt; 时,Thymeleaf 会尝试将其替换为完整的片段,包括标签。有以下特殊情况:

  • 如果片段不存在,Thymeleaf 不会插入任何内容
  • 如果片段由th:fragment="id" 标识,Thymeleaf 将删除th:fragment(例如:&lt;p th:fragment="foo"&gt;bar&lt;/p&gt; 给出&lt;p&gt;bar&lt;/p&gt;,无论tag 是什么)。
  • 如果片段由 dom 元素标识,Thymeleaf 会保留 dom 元素(例如:&lt;p id="foo"&gt;bar&lt;/p&gt; 给出 &lt;p id="foo"&gt;bar&lt;/p&gt;,无论 tag 是什么)

因此,如果您只想在 &lt;script&gt; 片段存在时包含它,您只需在它存在时通过 &lt;script th:fragment ...&gt;...&lt;/script&gt; 识别它,并通过以下方式将其包含在您的布局中:

<script th:replace="this :: script"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2011-05-29
    • 2021-10-21
    • 1970-01-01
    相关资源
    最近更新 更多