子模板引用父模板
父模板中要给子模板继承的部分用
th:fragment="模块名称"标明-
语法
-
引用父模板的
fragment- 父模板
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <div th:fragment="copy"> © 2011 The Good Thymes Virtual Grocery </div> </body> </html>- 子模板引用
<body> <div th:insert="~{footer :: copy}"></div> </body>只引用一个元素的话可以等价于下面这样写
<body> <div th:insert="footer :: copy"></div> </body> -
使用
css选择器父模板
<div id="copy-section"> © 2011 The Good Thymes Virtual Grocery </div>子模板引用
<body> <div th:insert="~{footer :: #copy-section}"></div> </body>-
footer是父模板的文件名,即父模板为footer.html,只要是放在了SpringMVC视图解析器的前后缀范围内即可 -
#copy-section就是常规的css选择器语法
-
-
使用三目运算符
<div th:insert="footer :: (${user.isAdmin}? #{footer.admin} : #{footer.normaluser})"></div>
-
三种引用方式
-
th:insert-- 把父模板的内容(包括标签)插入到子模板引用时的标签中,保留子模板引用的标签 -
th:replace-- 把父模板的内容(包括标签)插入到子模板引用时的标签中,删除子模板引用的标签 -
th:include(已经不推荐使用) -- 把父模板的内容(不包括标签)插入到子模板引用时的标签中,保留子模板引用的标签
三种引用方式的例子
-
父模板
<footer th:fragment="copy"> © 2011 The Good Thymes Virtual Grocery </footer> -
子模板
-
th:insert<body> <div th:insert="footer :: copy"></div> </body>效果
<div> <footer> © 2011 The Good Thymes Virtual Grocery </footer> </div> -
th:replace<body> <div th:replace="footer :: copy"></div> </body>效果
<footer> © 2011 The Good Thymes Virtual Grocery </footer> -
th:include<body> <div th:include="footer :: copy"></div> </body>效果
<div> © 2011 The Good Thymes Virtual Grocery </div>
-