一、前言
為什麼要使用模闆頁(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)。
如有侵權,請聯系 [email protected] 删除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。