Spring Boot学习笔记(十六):Thymeleaf 公共组件的抽取


       使用Thymeleaf项目开发中,经常会遇到网页中有大量的重复的内容,此时我们就需要考虑把重复的内容抽取出来,这样就会显得网页不是那么的臃肿。Thymeleaf模板引擎也为我们提供了这种功能。

       项目开发中,我们通常会在页面添加一个底边框,用于显示一些版权所有等信息。每个页面都需要显示的那种,此时我们就可以使用 Thymeleaf 模板为我们提供的公共组件抽取功能,来完成这一操作。

举例:如下代码为我们项目中多次重复使用的一段代码,我们需要对该内容就行抽取。

<footer>
	&copy; 2011 The Good Thymes Virtual Grocery
</footer>

1.如下是项目中 index.html 页面代码,需要对公共代码抽取

<head>
	<meta charset="utf-8">
	<title>index页面</title>
</head>
<body>
	<div>
		<span>省略部分代码</span>
		<span>省略部分代码</span>
	</div>
	<footer>
		&copy; 2011 The Good Thymes Virtual Grocery
	</footer>
<body>

第一种方式:

①使用th:fragment="片段名"的方式将其抽取成一个公共片段
<head>
	<meta charset="utf-8">
	<title>index页面</title>
</head>
<body>
	<div>
		<span>省略部分代码</span>
		<span>省略部分代码</span>
	</div>
	<footer th:fragment="copy">
		&copy; 2011 The Good Thymes Virtual Grocery
	</footer>
<body>
②.如果user.html页面也用到了这个片段,我们只需通过~{templatename::fragmentname}    (模板名::片段名) 的方式引入即可
<head>
	<meta charset="utf-8">
	<title>user页面</title>
</head>
<body>
	<div>
		<span>省略部分代码</span>
		<span>省略部分代码</span>
	</div>
	<!--引入抽取的公共片段-->
	<div th:insert=“~{index::copy}”></div>
<body>

第二种方式:

①只需要在公共组件添加一个 id 或 class 等只要css 能唯一定位到的属性即可   (此处以 id 为例)
<head>
	<meta charset="utf-8">
	<title>index页面</title>
</head>
<body>
	<div>
		<span>省略部分代码</span>
		<span>省略部分代码</span>
	</div>
	<footer id="copy">
		&copy; 2011 The Good Thymes Virtual Grocery
	</footer>
<body>
②.使用~{templatename::selector}  (模板名::选择器) 的方式引入即可
<head>
	<meta charset="utf-8">
	<title>user页面</title>
</head>
<body>
	<div>
		<span>省略部分代码</span>
		<span>省略部分代码</span>
	</div>
	<!--引入抽取的公共片段-->
	<div th:insert=“~{index :: #copy}”></div>
<body>

备注:我们也可以将公共组件单独写成一个 html ,使用文件名::片段名文件名::选择器 方式引入


额外内容:使用其他th 属性引入

       除去th:insert外,Thymeleaf 在公共片段引入方面,为我们提供了 2个属性可供我们选择,分别是:、th:replaceth:include,通过名称你应该也能够理解。三种引入公共片段的th属性区别如下:

  1. th:insert:将公共片段整个插入到声明引入的元素中

  2. th:replace:将声明引入的元素替换为公共片段

  3. th:include:将被引入的片段的内容包含进这个标签中

<!--公共片段-->
<footer th:fragment="copy">
	&copy; 2011 The Good Thymes Virtual Grocery
</footer>

<!--引入方式(可以使用省略~{}的方式,如下:)-->
<div th:insert="index :: copy"></div>
<div th:replace="index :: copy"></div>
<div th:include="index :: copy"></div>

<!--效果-->
<!--th:insert(直接将片段插入到div标签中)-->
<div>
    <footer>
    	&copy; 2011 The Good Thymes Virtual Grocery
    </footer>
</div>

<!--th:replace(直接使用片段将div标签替换掉)-->
<footer>
	&copy; 2011 The Good Thymes Virtual Grocery
</footer>

<!--th:include(直接将片段中的内容包含在div标签下)-->
<div>
	&copy; 2011 The Good Thymes Virtual Grocery
</div>

       附:Thymeleaf 开发参考手册一份:参考手册链接。这部分内容的介绍,可参考手册:8 Template Layout 章节


Thymeleaf 公共组件抽取内容,介绍到此为止

如果本文对你有所帮助,那就给我点个赞呗

End

发布了303 篇原创文章 · 获赞 67 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/lzb348110175/article/details/105207271