Thymeleaf提取公共页面

本文介绍了Thymeleaf中th:insert、th:replace和th:include三种方式实现公共页面的提取和引用。通过配置模版位置,创建公共页面如header.html,并使用th:fragment声明代码块,然后在目标页面使用th:replace等方式引入公共页面内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

三种方式

th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中,

th:replace:将代码块片段整个替换使用了th:replace的HTML标签中,

th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中

引入thymeleaf

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

配置

 spring:
   thymeleaf:
    encoding: UTF-8
    prefix: classpath:/templates/
    suffix: .html

注:prefix是字符串,不支持配置多个模版位置

公共页面

在sys文件夹下添加header.html文件

<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="head(title)">
    <title th:text="${title}"></title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!--bootstrap-->
    <link rel="stylesheet" th:href="@{/statics/css/bootstrap.min.css}">
</head>
</html>

注:th:fragment部分就是声明一个代码块
使用th:replace来添加需要引用的css和js文件

引入公共页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="sys/header::head(title='22222222')">
    <!--#parse("sys/header.html")-->
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
	
	<script src='https://gitee.com/fuyang_lipengjun/platform/widget_preview'></script>
	<style>
		.pro_name a{color: #4183c4;}
		.osc_git_title{background-color: #fff;}
		.osc_git_box{background-color: #fff;}
		.osc_git_box{border-color: #E3E9ED;margin: 20px;}
		.osc_git_info{color: #666;}
		.osc_git_main a{color: #9B9B9B;}
	</style>
</head>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值