SpringBoot利用thymeleaf设置公共页面
步骤:
1. 在templates下创建一个新的html页面,用于存放公共部分
2.将公共部分用div标签或是别的标签包裹起来(如下图中head标签中的内容)
th:fragment="my_css"此项就是给该标签命名,用于后续的使用
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:fragment="my_css">
<link rel="stylesheet" href="assets/css/bootstrap.min.css" th:href="@{/assets/css/bootstrap.min.css}">
<link rel="stylesheet" href="assets/css/owl.carousel.min.css"th:href="@{/assets/css/owl.carousel.min.css}">
<link rel="stylesheet" href="assets/css/flaticon.css"th:href="@{/assets/css/flaticon.css}">
<link rel="stylesheet" href="assets/css/slicknav.css"th:href="@{/assets/css/slicknav.css}">
<link rel="stylesheet" href="assets/css/animate.min.css"th:href="@{/assets/css/animate.min.css}">
<link rel="stylesheet" href="assets/css/magnific-popup.css"th:href="@{/assets/css/magnific-popup.css}">
<link rel="stylesheet" href="assets/css/fontawesome-all.min.css"th:href="@{/assets/css/fontawesome-all.min.css}">
<link rel="stylesheet" href="assets/css/themify-icons.css"th:href="@{/assets/css/themify-icons.css}">
<link rel="stylesheet" href="assets/css/slick.css"th:href="@{/assets/css/slick.css}">
<link rel="stylesheet" href="assets/css/nice-select.css"th:href="@{/assets/css/nice-select.css}">
<link rel="stylesheet" href="assets/css/style.css"th:href="@{/assets/css/style.css}">
</head>
3.在需要的地方使用 th:include 或 th:replace 或 th:insert
语法:th:insert="公共页面名 :: 要引用的代码块名字"
如:<div th:insert="common:: test"></div>
common就是公共页面名,test就是要引用的代码块名字
下例是引用步骤2中的代码:
<!doctype html>
<html lang="zxx" xmlns:th="http://www.thymeleaf.org">
<head>
<!-- CSS here -->
<link th:include="common::my_css">
</head>
三者的区别:如公共页面代码中
假设公共页面的名字就是common.html
<span th:fragment="test">
this is content!
</span>
1.th:insert (保留自己的标签,并将引用的标签内容及其标签都嵌入自己的标签内)
编译前:
<div th:insert="common:: test"></div>
编译后:
<div><span> this is content!</span></div>
2.th:replace(替换自己的标签)
编译前:
<div th:replace="common:: test"></div>
编译后:
<span> this is content!</span>
3.th:include(将被引用的标签中的内容嵌入自己的标签中)
编译前:
<div th:include="common :: test"></div>
编译后:
<div> this is content!</div>