thymeleaf中的模板布局

一.包括模板片段:

  1:定义和引用片段,我们经常会想要包含在模板片段来自其他模板。常见的用途是页脚、标题、菜单…;

为了做到这一点,Thymeleaf需要我们定义包含可用的片段,我们可以通过使用th:fragment属性。

  定义一个页面底部footer页面,在每一个需要的页面都可以用的模板,可以通过使用th:fragment属性

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

上面的代码定义了一个叫做副本的片段,我们可以很容易地包含在我们的主页上通过使用th:include or th:replace属性之一:

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

引用片段没有th:fragment:

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

页面引用:th:include="templatename::domselector"

templatename是要引入页面的路劲加上去掉后缀的名称,例如footer.html页面建立在/WEB-INF/templates/footer.html,所以templatename为footer;domselector就是dom选择器,即为th:fragment中的值,或是选择id
<body>
  ...
  <div th:include="footer :: #copy-section"></div>
  
</body

注意:

带有公共的页面,不要带有
<html>
    <head></head>
    <body></body>
</html>
直接写内容:
    <div th:fragment="copy">
      © 2011 The Good Thymes Virtual Grocery
    </div>
  

扩展写法,希望能灵活运用:

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

二.可参数化的片段签名

 可以像参数一样传入参数:

<div th:fragment="frag (onevar,twovar)">
    <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>

两种调用方式引入页面:

<div th:include="::frag (${value1},${value2})">...</div>
<div th:include="::frag (onevar=${value1},twovar=${value2})">...</div>

如果没有带参数,如下形式:

<div th:fragment="frag">
    ...
</div>

依然可以使用带参数的引入,但是必须使用第二种引入方式,另一种不行:如下是正确的引入方式

<div th:include="::frag (onevar=${value1},twovar=${value2})">

这样事实上,这将是相当于一个th:includeth:with的组合

<div th:include="::frag" th:with="onevar=${value1},twovar=${value2}">
原文地址:https://www.cnblogs.com/mymelody/p/7366197.html