Thymeleaf 是否原生支持 th:extend?如果不是,如何通过第三方库(如 Layout Dialect)实现?

解读

国内一线互联网公司(阿里、京东、美团等)在 Spring Boot 项目中普遍采用 Thymeleaf 做服务端渲染,面试官抛出“th:extend”这一关键词,目的是快速判断候选人是否真正落地过“页面继承/布局复用”场景。
很多候选人把“th:extend”误当成官方语法直接回答“支持”,结果现场手写代码时却编译报错,直接减分。
正确姿势是:先否定原生支持,再给出 Layout Dialect 的坐标、配置、模板结构、片段命名规范,并指出与 JSP Tiles、Sitemesh 的差异,体现“能落地、可维护、懂生态”。

知识点

  1. Thymeleaf 标准方言(Standard Dialect)只提供 th:replace / th:include / th:insert 三种“片段引用”方式,没有 th:extend。
  2. 官方额外方言列表里,nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect 专门解决“布局继承”问题,目前 3.x 版本对应 Thymeleaf 3.0+。
  3. 核心语法:
    • 布局页使用 layout:fragment="名称" 定义可覆盖区域
    • 内容页使用 layout:decorate="~{layout路径}" 进行装饰
    • 内容页使用 th:replace="~{:: #sectionId}" 或 th:block layout:fragment="名称" 填充区域
  4. 与 Spring Boot 的自动集成:只要依赖出现在 classpath,LayoutDialect 自动被 ThymeleafAutoConfiguration 注册,零 XML。
  5. 性能注意:布局解析结果会被 Thymeleaf 缓存,生产环境务必开启 spring.thymeleaf.cache=true,否则每次请求都会重新 build 模板树。
  6. 国内常见坑:
    • 使用 DevTools 热部署时,缓存策略与 Layout Dialect 的 NamedFragment 缓存冲突,可能出现“修改了片段不生效”,需要重启或清除 NamedFragmentSpec 缓存。
    • 路径前导“/”在可执行 JAR 与 IDE 中表现不一致,建议统一使用 classpath:/templates/ 相对路径。

答案

Thymeleaf 原生语法里不存在 th:extend。
要实现“页面继承”,必须引入第三方库 thymeleaf-layout-dialect,步骤如下:

  1. 在 pom.xml 增加坐标
    <dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    </dependency>
    Spring Boot 2.x 以上版本无需指定版本,由 starter 统一仲裁。
  2. 创建布局模板 /templates/layout/base.html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"> <head> <meta charset="UTF-8"/> <title layout:title-pattern="$CONTENT_TITLE - $LAYOUT_TITLE">后台系统</title> <th:block layout:fragment="extraCss"></th:block> </head> <body> <header>公共头部</header> <main layout:fragment="content"> <p>默认内容</p> </main> <footer>公共底部</footer> <th:block layout:fragment="extraJs"></th:block> </body> </html>
  3. 创建业务页面 /templates/user/list.html <html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/base}"> <head> <title>用户列表</title> <th:block layout:fragment="extraCss"> <link rel="stylesheet" th:href="@{/css/user.css}"/> </th:block> </head> <body> <th:block layout:fragment="content"> <h1>用户列表页真实内容</h1> </th:block> </body> </html>
  4. 启动应用,访问 /user/list,Thymeleaf 会先解析 base.html 得到骨架,再把 list.html 中同名的 layout:fragment 区域覆盖到骨架对应位置,最终输出完整 HTML。
  5. 如需多重继承,可继续在新布局里使用 layout:decorate,形成链式装饰,但建议不超过两层,避免调试困难。

拓展思考

  1. 微前端场景:如果部分页面需要由 Node SSR 或 Nginx 侧渲染,Layout Dialect 生成的 HTML 片段如何与前端 React/Vue 容器共存?
    答:可在布局页预留 <div id="microApp"> 插槽,通过 th:utext 输出后端拼接的 JSON,前端 hydrate 时做“孤岛渲染”,同时保留 SEO 友好。
  2. 灰度发布:同一套模板,不同版本如何按用户维度切换?
    答:自定义 IResourceResolver,把模板路径加上版本前缀,如 /templates/v1/layout/base.html,通过 ThreadLocal 传递灰度标识,Layout Dialect 解析时自动路由到对应版本目录。
  3. 安全加固:Layout Dialect 支持在布局层统一添加 CSRF 隐藏字段、Content-Security-Policy meta 标签,避免每个业务页重复书写;结合 Spring Security 的 Thymeleaf 方言,可直接使用 sec:authorize 控制整片区域是否渲染,实现“安全左移”。