SpringBoot中的thymeleaf布局

本文详细介绍如何使用Thymeleaf布局方言简化HTML模板的创建和管理,通过配置Pom依赖和SpringBean,实现页面布局的复用和美化。文章展示了如何在Spring MVC项目中集成Thymeleaf布局方言,并提供了布局文件和页面内容的具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Pom依赖

<dependency>
	<groupId>nz.net.ultraq.thymeleaf</groupId>
	<artifactId>thymeleaf-layout-dialect</artifactId>
	<version>2.2.2</version>
</dependency>

Spring Bean配置

    @Bean
    public LayoutDialect layoutDialect() {
        return new LayoutDialect();
    }

以上配置会使layout 命名空间可以引入五种属性:decorate, title-pattern, insert, replace, fragment

布局文件

resource/templates/layout/default.html

<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
  <title layout:title-pattern="$LAYOUT_TITLE - $CONTENT_TITLE">Layout title</title>
  <script src="common-script.js"></script>
</head>
<body>
  <header>
    <h1>Layout header</h1>
  </header>
  <section layout:fragment="content">
    <p>layout content</p>
  </section>
  <footer>
    <p>My footer</p>
    <p layout:fragment="custom-footer">layout footer</p>
  </footer>  
</body>
</html>

页面内容

test.html

<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/default.html}">
<head>
  <title>Content title</title>
  <script src="content-script.js"></script>
</head>
<body>
  <section layout:fragment="content">
    <p>my content</p>
  </section>
  <footer>
    <p layout:fragment="custom-footer">my footer</p>
  </footer>
</body>
</html>

controller部分

    @RequestMapping("/test.html")
    public String test(HttpServletRequest request) {
        return "test";
    }

此时访问test.html时就可以得到装饰之后的页面内容

参考:http://trumandu.github.io/2018/07/22/Thymeleaf%E5%B8%83%E5%B1%80/
https://www.cnblogs.com/ityouknow/p/5833560.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值