thymeleaf引入公共css、js

  有时候很多css文件是公共的,我们必须要在每个html文件中引入它们,其实我们可以利用Thymeleaf的模板布局,把这些css文件抽出来,同时如果有某个html文件专属的css文件,还可在引入模板的基础上单独引入该css文件。

首先,建立一个公共文件layout.html

 1 <!DOCTYPE html>
 2 <html xmlns:th="http://www.thymeleaf.org">
 3 <head th:fragment="common_head(title,links)">
 4     <meta charset="UTF-8">
 5     <title th:replace="${title}">CSDN博客</title>
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
 7     <link rel="shortcut icon" th:href="@{/resources/images/logo_ico_16.ico}" />
 8     <link rel="stylesheet" th:href="@{/resources/css/index.css}"/>
 9     <link rel="stylesheet" th:href="@{/resources/iconfont/iconfont.css}">
10     <link rel="stylesheet" th:href="@{/resources/css/common.css}"/>
11     <th:block th:replace="${links}" />
12 </head>
13 <body>
14  
15 </body>
16 </html>

  上面的“<head th:fragment="common_head(title,links)">”即为定义好的css模板,其中title和links为两个动态传入的变量,而th:block会在links值为空时自动隐藏,这样就可以实现除了css模板中的css文件之外,需要再单独引入css和不需要引入单独css两种情况。使用方法如下:

一、需要单独引入css

在实际的html文件中加入:

<head th:replace="layout :: common_head(~{::title},~{::link})">
    <title>测试公共css引入</title>
    <link rel="stylesheet" th:href="@{/resources/css/detail.css}"/>
    <link rel="stylesheet" th:href="@{/resources/css/profile.css}"/>
</head>

其中的title会自动将css模板中的title替换,而里面的多个link标签(只有一个link标签也可)也会替换th:block标签

二、不需要单独引入css

在实际的html文件中加入:

<head th:replace="layout :: common_head(~{::title},~{})">
    <title>测试公共css引入</title>
</head>

这种情况其实就是将传入的第二个变量置为空

但是这两种情况title都是必须的

原文地址:https://www.cnblogs.com/zsh-blogs/p/11005844.html