SpringBoot十六:模板引擎Thymeleaf抽取公共页面

介绍

1、抽取页面

假设footer.html,语法th:fragment="copy"其中copy就是片段名footer是模板名表明的是下面这段代码

<footer th:fragment="copy"> 
    &copy; 2011 The Good Thymes Virtual Grocery 
</footer>

2、引入公共片段

三种方式引入,都有区别(一般用th:replace,不会影响插入效果

  • th:insert="~{模板名 :: 片段名}"      :将公共片段整个插入到声明的元素中(一般是div声明,就是插入到div中) 
  • th:replace="~{模板名 :: 片段名}"   :将声明引入的元素替换成公共片段元素
  • th:include="~{模板名 :: 片段名}"   :将被引入的片段的内容替换成公共片段

开发:直接写th:replace="模板名 :: 片段名"也支持,而且方便。但是行内写法[[]]时,必须得用~{模板名 :: 片段名}

下面是模板引擎中的演示

1、抽取的页面footer.html,意思是模板名称是footer片段名称是footer

<footer th:fragment="copy">
     &copy; 2011 The Good Thymes Virtual Grocery 
</footer>

2、在test.html中分别用三种方式引入抽取的页面footer.html的片段

<body>
     ... 

    <div th:insert="footer :: copy"></div> 

    <div th:replace="footer :: copy"></div> 

    <div th:include="footer :: copy"></div> 
</body>

3、最终引入的效果

<body>
  ...
  <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>
</body>

效果说明:

1、th:insert引入的时候,直接<footer>插入片段标签插入到声明插入用的<div>标签中了(用div包含footer)

2、th:replace引入的时候,声明插入用的<div>不生效,插入的只是插入片段(div无效果)

3、th:replace引入的时候,div在,内容在,但是片段的footer标签没了,就是用div替换footer

猜你喜欢

转载自blog.csdn.net/qq_41055045/article/details/102564615