Thymeleaf3 (四)模板布局

在 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.htmlbase 代码片段的方式为:

<div th:insert="~{footer :: base}"></div>

其中 , ~{} 是可选的 , 我们可以去掉这层的包裹:

<div th:insert="footer :: base"></div>

如果 footer.htmlwelcome.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.htmlid="base" 片段的方式为:

<div th:insert="footer :: #base"></div>

th:replaceth: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>

转载于:https://my.oschina.net/u/4006362/blog/2394858

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值