Spring boot 如何使用视图解析器 thymeleaf 模板引擎整合html公共部分详情

94 阅读1分钟

在网站开发中 有的时候 会把网站的 公共的头部 公共的左导航 公共的尾部

抽取出来,然后哪里使用哪些引用 方便修改

下面 展示 通过 thymeleaf 引擎 来实现

先看官网文档介绍

www.thymeleaf.org/doc/tutoria…

1.png

他有两种声明 公共部分的方式

方式一 th:fragment=“copy”

方式二 也可以直接使用 选择器 来引用

id=“copy-section”

th:insert="~{footer :: #copy-section}

引用的时候 ~ 可以省略不写 th:insert=“footer :: copy” 这样写 也是可以的

2.png

引用公共 html 有三种方式

//方式一
 <div th:insert="footer :: copy"></div>
//方式二
  <div th:replace="footer :: copy"></div>
//方式三
  <div th:include="footer :: copy"></div>

区别

//方式一效果
  <div>
    <footer>
      &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
  </div>
//方式二效果
  <footer>
    &copy; 2011 The Good Thymes Virtual Grocery
  </footer>
//方式三效果
  <div>
    &copy; 2011 The Good Thymes Virtual Grocery
  </div>

根据自己需求 选择 使用

代码实现

3.png

4.png

引用方式

5.png

6.png

查看效果

7.png