应用场景:同一工程里不同页面所需使用的script文件和css文件大同小异,若每页都写一遍,修改时成本很高,故设置一公共的head文件,再导入它。
thymeleaf使用fragment语法进行导入。使用简介如下:
定义公共fragment:
<footer th:fragment="copy">
the content of footer
</footer>
引入公共fragment:
- th:insert:保留自己的主标签,保留th:fragment的主标签。
- th:replace:不要自己的主标签,保留th:fragment的主标签。
- th:include:保留自己的主标签,不要th:fragment的主标签。(官方3.0后不推荐)
导入片段:
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
结果为:
<div>
<footer>
the content of footer
</footer>
</div>
<footer>
the content of footer
</footer>
<div>
the content of footer
</div>
但以上方式都会替换原标签的内容。而我们的head标签虽大