如何检查 Thymeleaf 片段的定义 [英] How to check Thymeleaf fragment is defined

查看:18
本文介绍了如何检查 Thymeleaf 片段的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查使用 模板装饰而不是包含"技术?

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

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

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

...<div th:fragment="内容">...

</html>

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

解决方案

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

在下面,我将对任何给定的标签(divscriptspan、等)和 fragment 可接受的片段语法(this :: scriptthis :: contenttemplate :: #menu 等)

当你使用 时,Thymeleaf 总是会生成一个 ...</tag>.如果它不存在,则内容为空,给出 .如果片段存在,则内容成为片段的内容.例如,使用 <div th:"other :: #foo/> 作为片段 <p id="foo">bar</p> 给出

bar

当您使用 <tag th:replace="fragment"/> 时,Thymeleaf 会尝试将其替换为包含标签的完整片段.有以下特殊情况:

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

因此,如果您只想在

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆