https://blog.csdn.net/u010392801/article/details/80465800
**************************************************************************
最近在項目中應用到了 Thymeleaf,想寫一個通用的頁面來方便開發。網上有兩種方法一種是通過layout:fragment實現,另一種是通過th:replace或者th:include實現。但是都不能對子頁單獨引入 CSS、JS 文件,所以記錄下自己的實現方法。
我是通過th:replace的帶參數方法實現的:
這是我的目錄結構
我們拿<head></head>
部分來舉例子,首先定義模版頁 head.html:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head th:fragment="head(title,cssPaths)"> <title th:text="${title}"></title> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> <link rel="shortcut icon" th:href="@{/static/assets/demo/default/media/img/logo/favicon.ico}" /> <link rel="stylesheet" type="text/css" th:href="@{/static/assets/vendors/base/fonts/custom.min.css}" /> <!--begin::基礎樣式 --> <link rel="stylesheet" type="text/css" th:href="@{/static/assets/vendors/base/vendors.bundle.css}" /> <link rel="stylesheet" type="text/css" th:href="@{/static/assets/demo/default/base/style.bundle.css}" /> <!--end::基礎樣式 --> <!--begin::頁面樣式 --> <link rel="stylesheet" type="text/css" th:each="cssPath,status:${#strings.setSplit(cssPaths,',')}" th:href="@{${cssPath}}" /> <!--end::頁面樣式 --> </head> <body> </body> </html>
在定義 fragment 時把中的可變部分通過參數傳遞進來
title:標題
cssPaths:子頁單獨引入的所有 CSS 文件路徑
在<!--begin::頁面樣式 -->這里通過拆分和循環把 cssPaths 所包含的所有文件動態加載出來
引用頁面:index.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head th:replace="commons/head::head('首頁', '/static/assets/vendors/custom/datatables/datatables.bundle.css,'+ '/templates/index.css' )"></head> <body> </body> </html>
使用這種方法會把頁面的 CSS、JS 文件完全分離出去。但 HTML 和 CSS、JS 如果不在一根目錄下查看起來還是很不方便。在 SpringBoot 中 Templates 文件夾下的 CSS、JS 是不能被直接加載的, 需要特殊處理一下:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /** * @Author: Eric **/ @Configuration public class WebMvcConfig extends WebMvcConfigurationSupport { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //將templates目錄下的CSS、JS文件映射為靜態資源,防止Spring把這些資源識別成thymeleaf模版 registry.addResourceHandler("/templates/**.js").addResourceLocations("classpath:/templates/"); registry.addResourceHandler("/templates/**.css").addResourceLocations("classpath:/templates/"); //其他靜態資源 registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } }
在配置文件中static-path-pattern
和static-locations
就可以去掉了
這樣就實現了<head></head>
既有公用部分, 又可以在子頁面單獨引入 CSS 文件,JS 的也是同樣的方法。