head通用模板封装
一、场景描述
在head中经常会有一些公共的js和css,不想在每个html中重复的引入。
二、确定thymeleaf的版本
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- set thymeleaf version -->
<thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
</properties>
三、公共模板
文件路径:resources\templates\common.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="commonHead(title,links,styles,scripts)">
<meta charset="UTF-8" />
<title th:replace="${title}"></title>
<script th:inline="javascript">var ctx = "[[@{/}]]";</script>
<!-- 引入bootstrap -->
<link rel="stylesheet" href="/webjars/bootstrap/3.3.5/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/3.3.5/css/bootstrap.min.css}" />
<script src="/webjars/jquery/3.1.1/jquery.min.js" th:src="@{/webjars/jquery/3.1.1/jquery.min.js}"></script>
<script src="/webjars/bootstrap/3.3.5/js/bootstrap.min.js" th:src="@{/webjars/bootstrap/3.3.5/js/bootstrap.min.js}"></script>
<th:block th:replace="${links}" />
<th:block th:replace="${styles}" />
<th:block th:replace="${scripts}" />
</head>
</html>
四、引入
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en" th:replace="common::commonHead(~{::title},~{::link},~{},~{})">
<title>首页</title>
<!-- self -->
<link rel="stylesheet" href="/css/common.css" th:href="@{/css/common.css}" />
<link rel="stylesheet" href="/css/index.css" th:href="@{/css/index.css}" />
</head>
<body>
</body>
</html>
五、注意点
1. 在引入的时候使用 ~{::link} ,而不是 ~{::links} ;
2. 没有自定义style和script,需要使用 ,~{},~{} ,若果有,则是 ,~{::style},~{::script} ;