如果来自片段,如何向 thymeleaf head 标签添加其他内容?

Pau*_*ulB 6 templates thymeleaf spring-boot

在 Django 我可以这样做:

 <head>
{% block content %}

     (....) ---------> content from a partial template goes here.

{% endblock %}

     (....) ---------> I can add aditional stuff here if I need to.

<head>
Run Code Online (Sandbox Code Playgroud)

我喜欢的地方。(例如:在所有模板中使用相同的头部,但一个页面需要额外的 css 文件或脚本)

我知道在 thymeleaf 中,我需要将整个标签定义为一个片段,我无法再向其中添加任何其他内容并且需要按原样使用。

我的问题是我将如何在百里香叶中实现上述示例?

jua*_*umn 8

在资源/模板下创建一个名为片段的文件夹。创建文件 fragment.html 后,在你的脑海中:

 <head>

     <div th:replace="fragments/fragment :: fragment"></div>


     (....) ---------> you can add aditional stuff here if you need to.

<head>
Run Code Online (Sandbox Code Playgroud)

在你的 fragment.html 中:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head></head>
<body>
  <div th:fragment="fragment" th:remove="tag">
    (....) ---------> content from a partial template goes here.
  </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

th:replace实际上会用片段的标签替换主机标签

th:remove="tag"删除了包含的片段的容器 div

结果你应该得到:

 <head>

     (....) ---------> content from a partial template goes here.

     (....) ---------> you can add aditional stuff here if you need

<head>
Run Code Online (Sandbox Code Playgroud)