模板继承

子模板引用父模板

  • 父模板中要给子模板继承的部分用th:fragment="模块名称"标明

  • 语法

    1. 引用父模板的fragment

      • 父模板
      <!DOCTYPE html>
      <html xmlns:th="http://www.thymeleaf.org">
        <body>
          <div th:fragment="copy">
            &copy; 2011 The Good Thymes Virtual Grocery
          </div>
        </body>
      </html>
      
      • 子模板引用
      <body>
        <div th:insert="~{footer :: copy}"></div>
      </body>
      

      只引用一个元素的话可以等价于下面这样写

      <body>
        <div th:insert="footer :: copy"></div>
      </body>
      
    2. 使用css选择器

      父模板

      <div id="copy-section">
        &copy; 2011 The Good Thymes Virtual Grocery
      </div>
      

      子模板引用

      <body>
        <div th:insert="~{footer :: #copy-section}"></div>
      </body>
      
      • footer是父模板的文件名,即父模板为footer.html,只要是放在了SpringMVC视图解析器的前后缀范围内即可
      • #copy-section就是常规的css选择器语法
    3. 使用三目运算符

      <div th:insert="footer :: (${user.isAdmin}? #{footer.admin} : #{footer.normaluser})"></div>
      

三种引用方式

  1. th:insert -- 把父模板的内容(包括标签)插入到子模板引用时的标签中,保留子模板引用的标签
  2. th:replace -- 把父模板的内容(包括标签)插入到子模板引用时的标签中,删除子模板引用的标签
  3. th:include(已经不推荐使用) -- 把父模板的内容(不包括标签)插入到子模板引用时的标签中,保留子模板引用的标签

三种引用方式的例子

  • 父模板

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

    1. th:insert

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

      效果

      <div>
          <footer>
              &copy; 2011 The Good Thymes Virtual Grocery
          </footer>
      </div>
      
    2. th:replace

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

      效果

      <footer>
          &copy; 2011 The Good Thymes Virtual Grocery
      </footer>
      
    3. th:include

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

      效果

      <div>
          &copy; 2011 The Good Thymes Virtual Grocery
      </div>
      
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容