thymeleaf引入公共cssjs

Posted zsh-blogs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了thymeleaf引入公共cssjs相关的知识,希望对你有一定的参考价值。

  有时候很多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都是必须的

以上是关于thymeleaf引入公共cssjs的主要内容,如果未能解决你的问题,请参考以下文章

11SpringBoot-CRUD-thymeleaf公共页面元素抽取

thymeleaf公共页面元素抽取

thymeleaf

Thymeleaf静态资源引入方式及公共页面代码抽取

使用thymeleaf模板引擎抽取公共页面

vue工程化之公有CSSJS文件