当咱们在html页面使用thymeleaf时,常常会遇到这样的状况。有一些html片断在咱们全部页面都存在,形成了代码重复。遇到这种场景,咱们就能够把公共代码段抽取到一个公共页面,在须要使用它的地方,咱们引入就行。javascript
如上图所示,咱们首先在项目中新建一个html文件,名称为:include.html,位置如图中所示。css
<!DOCTYPE html> <!--suppress ALL--> <html lang="en"> <html xmlns:th="http://www.thymeleaf.org"> <head th:fragment=header(title)> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta id="viewport" name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"> <meta name="format-detection" content="telephone=no"/> <title th:text="${title}"></title> <link th:href="${application.webStaticUrl}+@{common/layer/need/layer.css}" rel="stylesheet"/> </head> <body> <!-- 通用JS --> <div th:fragment="footer"> <script th:src="${application.webStaticUrl}+@{common/jquery-2.1.0.js}"></script> <script type="text/javascript" th:src="${application.webStaticUrl}+@{common/pop_up/pop_up.js}"></script> <script th:src="${application.webStaticUrl}+@{common/layer/layer.js}"></script> </div> </body> </html>
上述代码中涉及的标签的使用方法这里不作赘述,你们能够自行百度html
咱们来解释下上面的代码,在公共页面咱们定义了header和footer两个代码片断(fragment翻译过来就是片断),其中在header片断咱们传递了一个参数,将它设置到title标签。java
你们能够看出,咱们将页面中head的公共部分和经常使用的js抽取出来,造成了这个公共页面.至于代码中的${application.webStaticUrl}是咱们项目本身定义的静态资源访问前缀,你们能够替换为本身项目中访问路径便可.jquery
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!--suppress ALL--> <html xmlns:th="http://www.thymeleaf.org"> <head lang="en"> <th:block th:include="include :: header('test')" /> <!--引入页面样式--> <!--<link rel="stylesheet" th:href="${application.webStaticUrl}+'test.css'" />--> </head> <body> <p>milogenius</p> <th:block th:include="include :: footer" /> </body> </html>
咱们来讲明下上面的代码,你们能够看到我用两对th:block标签和th:include标签来引入了咱们刚才定义的代码段,在引入header时,咱们传递了参数test,在引入header的下方,咱们也能够引入当前页面特有的样式表.web
咱们须要写一个跳转方法来展现刚才的页面,这里跳转方法你们本身写就行.
你们能够看到,咱们在引入header片断时传递的参数已经生效,页面也正常显示,那咱们看看刚才引入的代码段是否真正渲染到了页面?
经过右键查看网页源代码,咱们发现咱们已经成功的引入了公共页面,至此,大功告成!app