一、前言
为什么要使用模板页(Layout)
网站中往往有通用的布局,比如导航、底部等等,这些页面中共用的部分,就需要放在母版页(Layout)里面。
这样每个页面只用关注本页面要完成的功能/内容即可。提高了开发效率,也降低了公共部分的维护成本。
二、实现方式
1、Thymeleaf母版页示例
母版页代码(resources/templates/shared/layout1.html)
默认内容
母版页定义一个id=content的片段,以便子页面可以替换该内容
2、Thymeleaf子页面继承示例
子页面代码(resources/templates/demo/page1.html)
page1子页面内容
子页面引入模板layout1.html作为模板,并定义content同名片段覆盖母版页内容
3、 控制器代码示例
@RequestMapping("/page1")
ModelAndView page1(){
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("title","page1页面标题");
modelAndView.setViewName("demo/page1");
return modelAndView;
}
4、最终的渲染结果
page1页面标题page1子页面内容
三、备注
Thymeleaf语法/标签说明
语法/标签
说明
layout:fragment
定义模板片段,可以在子页面用同名片段覆盖
layout:decorator
引用Thymeleaf页面作为母版/模板
本文同步分享在 博客“Ken”(other)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。