Thymeleaf抽取公共部分

Thymeleaf抽取公共部分


Thymeleaf抽取公共部分方式一共是三种

th:insert
th:include
th:replace

下面来给例子演示:

1、抽取公共片段
<div th:fragment="copy">
&copy; 2011 The Good Thymes Virtual Grocery
</div>

2、引入公共片段
<div th:insert="~{footer::copy}"></div>
<div th:include="~{footer::copy}"></div>
<div th:replace="~{footer::copy}"></div>
三种方式可以写的方式有下面两种:
~{templatename::selector}:模板名::选择器
~{templatename::fragmentname}:模板名::片段名

1.模板名::片段名

demo.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
</head>
<body>
	<!--这里的footer是来自footer.html这个文件的文件中的footer,而非问价里面的footer标签-->
    <div th:insert="footer::copy"></div>
    <div th:replace="footer::copy"></div>
    <div th:include="footer::copy"></div>
</body>
</html>

footer.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>footer</title>
</head>
<body>
<!--要抽取的片段-->
<footer th:fragment="copy">
    &copy; 2011 The Good Thymes Virtual Grocery
</footer>
</body>
</html>

在这里插入图片描述

2.模板名::片段名

在这里插入图片描述
demo.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
</head>
<body>
    <div th:insert="footer::#bar"></div>
    <div th:replace="footer::#bar"></div>
    <div th:include="footer::#bar"></div>
</body>
</html>

footer.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>footer</title>
</head>
<body>
<!--要抽取的片段-->
<footer th:fragment="copy" id="bar">
    &copy; 2011 The Good Thymes Virtual Grocery
</footer>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_44932835/article/details/110296510