在 WEB 应用开发中 , 我们通常会将一些公共的代码片段如页眉 、 页脚 、 菜单等抽取出来放到一个或多个独立的文件里面 , 其他模板文件可以通过标签轻松的将这些代码片段引用进来 , 从而实现代码的复用性 。
在 Thymeleaf 中 , 你可以使用 th:fragment
来定义一个公共的代码片段 , 然后通过使用 th:insert 、 th:replace 、 th:include
(Thymeleaf 3.0 开始不再推荐使用 , 本文也将不再介绍它)属性可以实现将定义的公共代码片段引用到模板文件中 。
th:fragment
我们可以通过th:fragment
来定义一段公用的代码片段:
templates/footer.html
<div th:fragment="base">© 2017 fanlychie</div>
th:insert templates/welcome.html
文件中引用 footer.html
中 base
代码片段的方式为:
<div th:insert="~{footer :: base}"></div>
其中 , ~{}
是可选的 , 我们可以去掉这层的包裹:
<div th:insert="footer :: base"></div>
如果 footer.html
与 welcome.html
不在同级目录 , 如 templates/commons/footer.html
:
<div th:insert="@{commons/footer} :: base"></div>
类选择器 、 ID选择器等
除了可以使用 th:fragment
来定义一段公用的代码片段外 , 我们也可以使用类选择器 、 ID选择器等:
templates/footer.html
<div id="base">© 2017 fanlychie</div>
templates/welcome.html
文件中引用 footer.html
中 id="base"
片段的方式为:
<div th:insert="footer :: #base"></div>
th:replace
跟 th:insert
相似的 , th:replace
也可以用来引用公共的代码片段 。
不同的是 , th:insert
是直接将代码片段插入到标签体内 , 而 th:replace
则是用代码片段直接替换标签体内容 。
举个栗子:
<!-- <div><div id="base">© 2017 fanlychie</div></div> -->
<div th:insert="footer :: base"></div>
<!-- <div id="base">© 2017 fanlychie</div> -->
<div th:replace="footer :: base"></div>
th:fragment 参数使用
使用 th:fragment
来定义一个代码片段时 , 它允许你指定一组参数 , 语法: th:fragment="fragmentname(arg1, arg2, ...)
"
<div th:fragment="crumbs(parent, child)">
<span th:text="|${parent} > ${child}|"></span>
</div>
<!-- 用户中心 > 我的订单 -->
<div th:replace="::crumbs('用户中心', '我的订单')"></div>
th:assert
断言 , 它可以同时指定多个表达式 , 每个表达式的结果评估值必须为 true , 否则它将会抛出一个异常 。 语法: th:assert="expression1, expression2..." :
<div th:replace="::crumbs(${parentMenuName}, ${childMenuName})" th:assert="${!#strings.isEmpty(parentMenuName), !#strings.isEmpty(childMenuName)}"></div>
定义局部变量
使用 th:with 属性可以定义局部变量:
<p th:with="name='fanlychie'">
<span th:text="${name}"></span>
</p>
同时定义多个局部变量时 , 用英文 , 号分隔开:
<p th:with="name=${user.name},age={user.age}">
......
</p>