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

最近在项目中应用到了 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>
</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 的也是同样的方法。

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值