之前参考网上的各种方法,均为达到期望的效果,于是到Thymeleaf 官网逛了下,找到官网的例子来实现了:
以fragment方式分离公有css和js,
以replace+参数的方式传入每个页面单独的css和js.
直接上栗子:
公有css(存放在templates/common/htmlHead.html中):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="common_header(title,links)">
<!-- Common styles and scripts -->
<title th:replace="${title}">The awesome application</title>
<meta charset="utf-8"></meta>
<meta http-equiv="X-UA-Compatible" content="IE=edge"></meta>
<meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"></meta>
<meta name="description" content=""></meta>
<meta name="author" content=""></meta>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"></meta>
<link rel="icon" href="/img/icon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="/favicon.ico" />
<link th:href="@{/webjars/bootstrap/3.3.7/dist/css/bootstrap.css}" rel="stylesheet">
<link href="css/common/top_header.css" rel="stylesheet">
<link href="css/common/bottom_footer.css" rel="stylesheet">
<!--<link th:href="${myCss}" rel="stylesheet">-->
<link th:href="@{/webjars/cropper/2.3.4/dist/cropper.css}" rel="stylesheet">
<link href="css/common/rspMsg.css" rel="stylesheet">
<link href="css/common/common.css" rel="stylesheet">
<!--/* Per-page placeholder for additional links */-->
<th:block th:replace="${links}" />
</head>
一般页面调用公有css,并使用自己的css:
<!DOCTYPE html>
<html lang="zh-CN">
<head th:replace="common/htmlHead :: common_header(~{::title},~{::link})">
<title>设置</title>
<link rel="stylesheet" href="css/index.css">
</head>
</html>
公有js的提取方式是一样的:
<!DOCTYPE html>
<html lang="zh-CN">
<div th:fragment="common_js(scripts)">
<script th:src="@{/webjars/vue/2.3.4/dist/vue.js}"></script>
<script th:src="@{/webjars/vue-resource/1.3.1/dist/vue-resource.js}"></script>
<script th:src="@{/webjars/jquery/3.2.1/dist/jquery.js}"></script>
<script th:src="@{/webjars/tether/1.4.0/js/tether.js}"></script>
<script th:src="@{/webjars/bootstrap/3.3.7/dist/js/bootstrap.js}"></script>
<script th:src="@{/webjars/cropper/2.3.4/dist/cropper.js}"></script>
<script src="js/common/top_header.js"></script>
<script src="js/common/common.js"></script>
<!--/* Per-page placeholder for additional js */-->
<th:block th:replace="${scripts}" />
</div>
</html>
公有js的使用包一层div即可:
......
<body>
......
<!--使用公有js-->
<div th:replace="common/htmlJS::common_js(~{::script})">
<!--每个页面自己的js-->
<script src="js/index.js"></script>
</div>
</body>
</html>
测试结果可用,具体解释请参考Thymeleaf官方文档
另外本人使用的SpringBoot版本是1.5.4,默认的thymeleaf不是3.0版本,上面的测试需要thymeleaf 3.0版本才可以,需要修改下pom.xml文件,添加以下配置即可:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- set thymeleaf version -->
<thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
</properties>
最后帮朋友打个小广告