抽取公共元素
元素抽取:
<div th:fragment="copy"> © 2011 The Good Thymes Virtual Grocery </div>
标签: th:fragment="给要抽取部分取名"
元素导入:
<div th:insert="~{footer :: copy}"></div> 早行内写法中只能使用~{}
或者: <div th:insert="footer :: copy"></div> 其他的情况都可以使用这种简便的写法
相当于:
~{templatename : : fragmentname} 模板名::片段名
~{templatename : : selector} 模板名::选择器名
例如:
在dashboard 页面中:
<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/#" th:text="${session.loginUser}">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>
和list 页面中有这一部分是一样的,所以给nav 标签加上:th:fragment ="name"
在list 页面的引入:
<div th:insert="~{dashboard::topbar}"></div>
引入公共元素的方式:
th:insert :会将整个片段插入div 中
th:replace : 整个片段替换div
th:include : div 中没有片段的最外层标签
公共片段:
<footer th:fragment="copy"> © 2011 The Good Thymes Virtual Grocery </footer>
引入方式:
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
不同的效果:
<div> <footer> © 2011 The Good Thymes Virtual Grocery </footer> </div>
<footer> © 2011 The Good Thymes Virtual Grocery </footer>
<div> © 2011 The Good Thymes Virtual Grocery </div>
当我们不完全使用引入的片段,而是对其中的内容有一定的修改
在提取公共片段的地方设置判断的条件和参数,在引入公共参数的时候传入响应的参数
例如:
公共片段:
<a class="nav-link active" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#" th:href="@{/index.html}"
th:class="${active}=='index'?'nav-link active':'nav-link'"> 传入的参数=index 连接高亮,不是index 则不高亮
设置判断的条件
引入片段时传入参数:
<div th:replace="commons/bar::#sidebar(active='side')"></div> 在该页面上上述链接需要是高亮的所以要传入参数active=index