Spring Boot中Thymeleaf模板如何分离head标签CSS/JS库实现复用?
完全可以通过Thymeleaf的模板片段机制实现公共资源的复用,无需重复编写引入代码,以下是最适合入门开发者的实操方案:
方案一:原生Thymeleaf片段(无额外依赖,推荐入门使用)
步骤1:创建公共资源片段文件
在Spring Boot项目的src/main/resources/templates目录下新建common文件夹,在其中创建common_head.html文件,内容如下:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" lang="en"> <!-- 定义名为commonHead的片段,存放所有公共CSS、图标、字体引入 --> <head th:fragment="commonHead"> <link rel="shortcut icon" th:href="@{/assets/images/favicon.png}" type="image/x-icon"> <link rel="icon" th:href="@{/assets/images/favicon.ico}" type="image/x-icon"> <!-- Google font--> <link href="https://fonts.googleapis.com/css?family=Ubuntu:400,500,700" rel="stylesheet"> <!-- Font Awesome --> <link th:href="@{/assets/css/font-awesome.min.css}" rel="stylesheet" type="text/css"> <!--ico Fonts--> <link rel="stylesheet" type="text/css" th:href="@{/assets/icon/icofont/css/icofont.css}"> <!-- Required Framework --> <link rel="stylesheet" type="text/css" th:href="@{/assets/plugins/bootstrap/css/bootstrap.min.css}"> <!-- waves css --> <link rel="stylesheet" type="text/css" th:href="@{/assets/plugins/Waves/waves.min.css}"> <!-- Style.css --> <link rel="stylesheet" type="text/css" th:href="@{/assets/css/main.css}"> <!-- 预留扩展位,支持页面传入独有的CSS/JS引入 --> <th:block th:replace="${extraHead} ?: ~{}" /> </head> </html>
步骤2:在业务页面引入公共片段
修改你的login.html等页面,直接引入上面定义的片段即可:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" lang="en"> <head> <title>Login Form</title> <!-- 引入公共头部片段 --> <th:block th:replace="common/common_head :: commonHead" /> <!-- 这里可以写当前页面独有的CSS引入 --> <link rel="stylesheet" th:href="@{/assets/css/login-custom.css}"> </head> <body> <!-- 页面业务内容 --> </body> </html>
常用引入属性说明
th:replace:直接将当前标签替换为片段内容,不会保留原标签th:insert:保留当前标签,将片段内容插入到标签内部th:include:仅插入片段的内容,丢弃片段的外层标签(Thymeleaf 3.x版本已不推荐使用)
方案二:Thymeleaf Layout Dialect(适合整站统一布局)
如果除了公共资源,还需要复用导航栏、页脚、侧边栏等全站公共组件,可以使用Thymeleaf的布局方言实现母版页机制,只需要在项目依赖中引入Thymeleaf布局方言包后,定义全局母版页,所有业务页只需编写核心内容区域即可。
简单使用逻辑
- 定义母版页
layout/default.html,包含公共head、导航、页脚,用layout:fragment标记可替换的内容区域 - 业务页用
layout:decorate="~{layout/default}"声明继承母版,在对应fragment中编写业务内容即可
注意:两种方案都无需额外配置,Spring Boot默认会自动扫描Thymeleaf的模板路径和片段定义。
内容的提问来源于stack exchange,提问作者Jonathan Smith
相关产品推荐
相关产品推荐

