【问题标题】:How to add additional content to thymeleaf head tag if it comes from a fragment?如果它来自片段,如何将其他内容添加到百里香头部标签?
【发布时间】:2018-01-26 02:26:59
【问题描述】:
在 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 中我需要将整个标签定义为一个片段,我不能再向其中添加任何其他内容并且需要按原样使用。
我的问题是如何在百里香中实现上述示例?
【问题讨论】:
标签:
templates
spring-boot
thymeleaf
【解决方案1】:
只需将其添加到 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>
【解决方案2】:
在名为片段的资源/模板下创建一个文件夹。创建文件 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>