SpringBoot中的thymeleaf布局

Pom依赖

<dependency>
	<groupId>nz.net.ultraq.thymeleafgroupId>
	<artifactId>thymeleaf-layout-dialectartifactId>
	<version>2.2.2version>
dependency>

Spring Bean配置

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

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

布局文件

resource/templates/layout/default.html


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

页面内容

test.html


<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/default.html}">
<head>
  <title>Content titletitle>
  <script src="content-script.js">script>
head>
<body>
  <section layout:fragment="content">
    <p>my contentp>
  section>
  <footer>
    <p layout:fragment="custom-footer">my footerp>
  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

你可能感兴趣的:(Java&Javaweb)