fragment介绍
fragment类似于JSP的tag,在html中文件中,可以将多个地方出现的元素块用fragment包起来使用。
fragment使用
定义fragment
所有的fragment可以写在一个文件里面,也可以单独存在,例如
<footer th:fragment="copy">
the content of footer
</footer>
fragment的引用
- th:insert:保留自己的主标签,保留th:fragment的主标签。
- th:replace:不要自己的主标签,保留th:fragment的主标签。
- th:include:保留自己的主标签,不要th:fragment的主标签。(据说,官方3.0后不推荐)
导入片段:
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
结果为:
<div>
<footer>
the content of footer
</footer>
</div>
<footer>
the content of footer
</footer>
<div>
the content of footer
</div>
在Springboot中,默认读取thymeleaf文件的路径是:src/main/resource/templates,静态文件为src/main/resource/static,这个默认值可以在配置文件中修改:spring.thymeleaf.prefix=classpath:/templates/
所有在调用fragment时,是默认从thymeleaf的根路径开始设置的:
例如 <head th:replace="/include/header::head" >
从读取templates/include/header.html中 fragment=head的代码块
注意: th:block 和th:replace 和th:text 和th:fragment等配合使用。
使用场景比较如,全局CSS,全局JS等。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<th:block th:fragment="headblock(title)">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title th:text="${title}">AdminLTE 2 | Starter</title>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="/jslib/adminlte/bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/jslib/adminlte/bower_components/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="/jslib/adminlte/bower_components/Ionicons/css/ionicons.min.css">
<link rel="stylesheet" href="/jslib/adminlte/dist/css/AdminLTE.min.css">
<link rel="stylesheet" href="/jslib/adminlte/dist/css/skins/skin-blue.min.css">
</th:block>
使用的时候
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<div th:replace="common/common :: headblock('AdminLTE 2 | Starter')"></div>
<!-- 引入自定义CSS -->
</head>
其它可以使用DIV或者其它html标签
<footer th:fragment="main-footer" class="main-footer">
<!-- To the right -->
<div class="pull-right hidden-xs">
Anything you want
</div>
<!-- Default to the left -->
<strong>Copyright © 2016 <a href="#">Company</a>.</strong> All rights reserved.
</footer>
<th:block th:fragment="commonfooterjs">
<script src="/jslib/adminlte/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/jslib/adminlte/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="/jslib/adminlte/dist/js/adminlte.min.js"></script>
</th:block>
使用
<!-- Main Footer -->
<div th:replace="common/common :: main-footer"></div>
<!-- 引入通用javaScript -->
<div th:replace="common/common :: commonfooterjs"></div>
<!-- 引入自定义javaScript -->
来源:oschina
链接:https://my.oschina.net/lenglingx/blog/4469282