通过th:fragment提取公共的代码
方式一:
抽取一个公共片段: th:frament="片段名"
引入公共片段的方式有三种:
th:insert
:将公共片段整个替换到标签中th:replace
:公共片段直接对标签以及标签内部的内容进行替换th:include
:公共片段(不包括自己的主标签)对标签内容进行替换
在页面中引用: ~{模板名 :: 片段名}
方式二:
在要提取的公共片段上添加能够唯一标识该标签的id或css等属性,之后通过 {模板名 :: 选择器}
的方式引用。
样例
需要抽取的公共片段component.html,我们可以将多个需要抽取的片段写在一个文件里面:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<div th:fragment="com1">
111
</div>
<div th:fragment="com2">
222
</div>
<div id="com3">
333
</div>
</html>
在页面中使用:
<!DOCTYPE html>
<!--把html 的名称空间,改成:`xmlns:th="http://www.thymeleaf.org"` 会有语法提示-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>hello</title>
<link rel="stylesheet" th:href="@{app.css}">
</head>
<body>
<div th:replace="~{component::com1}"></div>
<!--保留原来的标签-->
<div th:insert="~{component::com2}"></div>
<!--只需要在公共组件添加一个 id 或 class 等只要css 能唯一定位到的属性即可 (此处以 id 为例)-->
<div th:insert="~{component::#com3}"></div>
</body>
</html>
结果:
注意:在调用fragment时是从Thymeleaf文件的根路径:src/main/resource/templates开始的,如果像读取子路径下的代码块应该配置相应的路径。
传递参数
定义:
<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:include="::frag" th:with="onevar=${value1},twovar=${value2}">)
案例:实现导航栏
新建一个模板布局 _framents.html :
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:fragment="head(title)">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title th:replace="${title}">模板布局</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">
</head>
<body>
<!--导航-->
<nav th:fragment="menu(n)" class="ui m-bg attached segment animated fadeInDown" style="z-index: 999!important;">
<div class="ui container">
<!--stackable:可堆叠,屏幕小的时候会堆叠到一块,用于适应移动端网页适配-->
<div class="ui secondary stackable menu">
<!--teal颜色header-->
<h2 class="ui teal header item">导航栏</h2>
<!--home icon:图标-->
<a th:href="@{/page1}" class="teal m-item item" th:classappend="${n==1} ? 'active'"></i>第一页</a>
<a th:href="@{/page2}" class="teal m-item item" th:classappend="${n==2} ? 'active'"></i>第二页</a>
<a th:href="@{/page3}" class="teal m-item item" th:classappend="${n==3} ? 'active'"></i>第三页</a>
<!--right:靠右-->
<div class="right item m-mobile-hide">
<!--可以加transparent:透明-->
<div class="ui icon input ">
<input type="text" placeholder="Search....">
<i class="search link icon"></i>
</div>
</div>
</div>
</div>
</nav>
</br>
</br>
</br>
</br>
</body>
</html>
新建三个页面:page1.html、page2.html、page3.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="_fragments :: head(~{::title})">
<meta charset="UTF-8">
<title>第二页</title>
<link rel="stylesheet">
</head>
<body>
<nav th:replace="_fragments :: menu(2)" class="ui inverted attached segment"></nav>
<h1>第二页</h1>
</body>
</html>
运行结果: