Ken的杂谈
  • Ken的杂谈 (current)
  • 关于
  • 杂谈
    Java Spring Spring Boot Spring Cloud MyBatis C# .NET Core .NET ASP.NET Core ASP.NET ClassLibrary Mono 数据库 MySQL SQL Server 网络 缓存 Web Linux CentOS Ubuntu macOS Windows openEuler Nginx ServiceStack JS/JQ 正则 工具 IDE Grafana Exceptions CI/CD Solution 微服务 Arch Docker 杂谈
  • 系列
    Java 快速入门系列教程 Spring Boot 入门教程 Spring Boot 2.x 入门教程 Spring Cloud 入门教程 .NET Core 快速入门教程 ASP.NET Core 2.1 入门教程 CentOS 7 快速上手教程 Ubuntu快速上手入门教程 Hyper-V基础教程 Docker入门教程
  • GitHub

Thymeleaf使用技巧:使用片段(fragment)实现母版页(Layout)功能

Web Java Spring Boot @ 2017-09-10 22:41:14 · 阅读:(12224)

一、前言

  • 为什么要使用模板页(Layout)

网站中往往有通用的布局,比如导航、底部等等,这些页面中共用的部分,就需要放在母版页(Layout)里面。
这样每个页面只用关注本页面要完成的功能/内容即可。提高了开发效率,也降低了公共部分的维护成本。

如果你还未使用过Thymeleaf,可以先阅读:使用Spring Boot+Thymeleaf模板引擎开发Web应用

二、实现方式

1、Thymeleaf母版页示例

  • 母版页代码(resources/templates/shared/layout1.html)
<!DOCTYPE html>
<html lang="en">
<head>
    <title th:text="${title}"></title>
</head>
<body>
<div layout:fragment="content">
    默认内容
</div>
</body>
</html>

母版页定义一个id=content的片段,以便子页面可以替换该内容

2、Thymeleaf子页面继承示例

  • 子页面代码(resources/templates/demo/page1.html)
<div layout:decorator="shared/layout1">
    <div layout:fragment="content">
        page1子页面内容
    </div>
</div>

子页面引入模板layout1.html作为模板,并定义content同名片段覆盖母版页内容

3、 控制器代码示例

@RequestMapping("/page1")
ModelAndView page1(){
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.addObject("title","page1页面标题");
    modelAndView.setViewName("demo/page1");
    return modelAndView;
}

4、最终的渲染结果


<!DOCTYPE html>
<html>
<head>
    <title>page1页面标题</title>
</head>
<body>
    <div>
        page1子页面内容
    </div>
</body>
</html>

三、备注

Thymeleaf语法/标签说明

语法/标签 说明
layout:fragment 定义模板片段,可以在子页面用同名片段覆盖
layout:decorator 引用Thymeleaf页面作为母版/模板

Ken的杂谈

本文由 ken.io 创作,采用CC BY 3.0 CN协议 进行许可。 可自由转载、引用、甚至修改,但需署名作者且注明出处。

Web Java Spring Boot

随笔目录


    © Copyright 2012-2025 Ken的杂谈

    豫ICP备10025012号

    ASP.NET Core(6.0) on Linux