thymeleaf layout

thymeleaf是spring boot默认的模板引擎,属于比较新的模板引擎,这个提供了很多新功能,页面就是原生的html页面,并且通过标签的方式能彻底的进行前后端分离。通常的时候不管是管理系统还是网站系统,总会有很多共用的部分,例如header和footer等等。
如果使用的是springboot 1.5.9版本,则它内置的thymeleaf版本是1.4.2,在官网上可以看到,现在thymeleaf都都已经升级到了3.0版本,对于layout布局的这种,3.0支持insert标签。

更改thymeleaf版本

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!-- set thymeleaf version -->
        <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
    </properties>

使用 replace

根据官网的例子,我们有一个文件footer.html文件,这个文件位于 layout文件夹下,代码如下

<!DOCTYPE html>\
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="copy">
    &copy; 2011 The Good Thymes Virtual Grocery
</div>
</body>
</html>

然后在另外一个页面中引用

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

这样就把刚才的footer页面引用进来了.
当然我们在被引入页面中也不一定非得使用fragment ,在引用的时候 "::"是一个选择器。可以为footer的div起一个id = “footer”, 在引用的时候使用 ~{layout/footer::#footer}这样也能引入。如果不加选择器,则引用的就是整个页面,例如像下面这种引用方式

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

这样就会把整个footer.html页面的内容引用进来

其他布局元素 replace,insert,include

  • replace :替换元素内容 2.0版本和3.0版本均支持
  • **insert **,3.0版本新增的标签,会把需要的内容插入到父元素的内部
  • include ,3.0版本已经推荐放弃使用 上述说的比较抽象,具体看生成的代码便一目了然
<div th:replace="layout/footer::copy"></div>
<div th:insert="~{layout/footer:: copy}"></div>
<div th:include="layout/footer::copy"></div>

生成后的代码

<!--replace 在此处,替换div元素-->
<div>
    &copy; 2011 The Good Thymes Virtual Grocery
</div>
<!--insert 在此处 footer中copy元素的内容会被插入到 div中-->
<div><div>
    &copy; 2011 The Good Thymes Virtual Grocery
</div></div>
<!--include,footer中的内容会被插入到div中-->
<div>
    &copy; 2011 The Good Thymes Virtual Grocery
</div>

仔细观察生成后的代码,对这块thymeleaf这块的使用就会比较清晰了。这样该使用哪个,就会变得比较自如。

猜你喜欢

转载自my.oschina.net/u/2457218/blog/1615661