一、定义模板
可通过th:fragment定义模板片段和id定义模板片段
th:fragment的值为模板片段的名称
One通过th:fragmen定义模板片段;
Two通过id定义模板片段;
Three和four为了引用时,显示include和replace的区别;
Five模板片段传参。
myfrag.html
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <body> <div th:fragment="One"> This is One! </div> <div id="Two"> This is Two! </div> <div th:fragment="Three" style="background: deepskyblue"> This is Three! </div> <div th:fragment="Four" style="background: deepskyblue"> This is Four! </div> <div th:fragment="Five(onevar,twovar)"> <p th:text="${onevar} + ' - - - - - ' + ${twovar}"></p> </div> <div th:fragment="Six"> This is Six! </div> <div th:fragment="Seven"> This is Seven! </div> </body> </html>
二、引用模板
用th:include或th:replace引入模板
其值为"模板名称::片段"
扫描二维码关注公众号,回复:
920100 查看本文章
index.html
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> </head> <body> <div th:include="myfrag::One"></div> <div th:include="myfrag::#Two"></div> <div th:include="myfrag::Three" style="background: red"></div> <div th:replace="myfrag::Four" style="background: red"></div> <div th:include="myfrag::Five ('ThisOne','ThisTwo')"></div> <div th:include="myfrag::Six" style="background: red"></div> <div th:replace="myfrag::Seven" style="background: red"></div> </body> </html>
三、include和replace的区别
include是本div包含引入div的内容
replace是本div替换引入div
定义模板如:
<div th:fragment="frag1" id="frag1" > frag1 </div> <div th:fragment="frag2" id="frag2"> frag2 </div>
引入模板如:
<div th:include="myfrag::frag1" id="inc"></div> <div th:replace="myfrag::frag2" id="rep"></div>
相当于:
<div id="inc">frag1</div> <div id="frag2">frag2</div>
四、传参
定义模板如:
<div th:fragment="Five(onevar,twovar)"> <p th:text="${onevar} + ' - - - - - ' + ${twovar}"></p> </div>
引入模板如:
<div th:include="myfrag::Five ('ThisOne','ThisTwo')"></div>