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

问题描述 投票:0回答:2

在 django 中我可以做:

 <head>
{% block content %}

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

{% endblock %}

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

<head>

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

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

我的问题是我将如何在 thymeleaf 中实现上述示例?

templates spring-boot thymeleaf
2个回答
13
投票

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

 <head>

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


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

<head>

在你的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>

th:replace 实际上会用片段的

替换主机标签

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

结果你应该得到:

 <head>

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

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

<head>

3
投票

只需将其添加到 head 标签中即可:

<head>
  <th:block th:replace="fragments/headContent :: baseContent"></th:block>
  <!-- other blocks -->
</head>

在片段文件中:

<head>
  <th:block th:fragment="baseContent">
    <link href="/css/bootstrap.min.css" rel="stylesheet"> 
    <style> **your style tag content** </style>
  </th:block>
</head>
© www.soinside.com 2019 - 2024. All rights reserved.