SpringBoot中的thymeleaf布局

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="$DECORATOR_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布局/
https://www.cnblogs.com/ityouknow/p/5833560.html

posted @ 2019-07-26 14:47  商商-77  阅读(875)  评论(0编辑  收藏  举报