th:insert、th:replace、th:include抽取和引用页面公共片段、传参等

一、抽取公共片段

  • th:fragment  给片段命名

将公共片段抽取出来,并在顶级标签内使用th:fragment给该片段命名。

例如:将公共片段抽取出来放到comment/bar.html中:

     

<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">
  <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Company name</a>
  <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
  <ul class="navbar-nav px-3">
    <li class="nav-item text-nowrap">
      <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a>
    </li>
  </ul>
</nav>

这样我们就抽取了一个名叫topbar的公共片段。

二、引入公共片段

1.三种引入片段的方式:

  • th:insert :将公共片段插入到声明引入的标签中
  • th:replace:将公共片段替换掉声明引入的标签
  • th:include:将公共片段中的内容包含进声明引入的标签内。

这三中引入的效果如下:

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

th:insert :

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

效果:
<div>
<footer>
&copy; 2011 The Good Thymes Virtual Grocery
</footer>
</div>

th:replace:

<div th:replace="footer :: copy"></div>
效果:
<footer>
&copy; 2011 The Good Thymes Virtual Grocery
</footer>

th:include:

<div th:include="footer :: copy"></div>
效果:
<div>
&copy; 2011 The Good Thymes Virtual Grocery
</div>

2.引入片段的表达式

在上边例子中我们可能有疑问 footer :: copy 这是什么意思?

其实这是一种引入片段的表达式之一,下面我们讲两种引入片段的表达式。

(1) 通过片段名引入片段的表达式: ~{模板名::片段名}

  如我们需要引入上边第一部分演示的片段,我们需要这样写

<div th:replace="~{commons/bar::topbar}"></div>

注意 ~{}可以省略,开发中常常不会写~{}的方式来引入,而是通过下边这种,更加简洁

<div th:replace="commons/bar::topbar"></div>

(2)通过选择器引入片段的表达式:~{模板名::选择器}

例如引入id为user的片段:

<div th:replace="commons/bar::#user"></div>

#号为id选择器

三、引用片段并传参

1.传递参数

只需要在表达式后边跟个小括号即可传递参数,小括号内通过键值对的方式设置值(key=value)

<div th:replace="commons/bar::topbar(username='zhangsan')"></div>

 2.获取参数

 在目标页面(引用片段表达式中模板名对应的页面)通过变量表达式${} 获取值即可。

<h4 th:text="${username}"></h4>
原文地址:https://www.cnblogs.com/bear7/p/13491428.html