Thymeleaf模版--子页面单独引入CSS、JS文件

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-patternstatic-locations就可以去掉了
这样就实现了<head></head>既有公用部分, 又可以在子页面单独引入 CSS 文件,JS 的也是同样的方法。

 

posted @ 2018-11-26 16:35  zhao1949  阅读(4057)  评论(0编辑  收藏  举报