Thymeleaf抽取公共部分
Thymeleaf抽取公共部分方式一共是三种
th:insert
th:include
th:replace
下面来给例子演示:
1、抽取公共片段
<div th:fragment="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">
© 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">
© 2011 The Good Thymes Virtual Grocery
</footer>
</body>
</html>