1. 概述
在web开发中,我们经常会将公共头,公共尾,菜单等部分提取成模板供其它页面使用。在thymeleaf中,通过th:fragment、th:include、th:replace、参数化模板配置、css选择器加载代码块等实现。下文通过例子来说明用法:
- fragment语法
- 通过 th:fragment 和 css选择器加载代码块
- th:include 和 th:replace
- 参数化模板配置
Thymeleaf基本搭建和配置可以参考其他网站的配置实例,这里不详细说明。
2.引入头文件
首先我们讲述web项目里的js,css如何放到一个公共页面,用thymeleaf模板语法调用呢?其实thymeleaf里有个标签可以使用:
initHead.html
<th:block id="initHead"><!-- 可以充当HTML标签,但在模板执行后该标签会消失 -->
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<script type="text/javascript" th:src="@{/resources/js/share/backstage/jquery.js}"></script>
<!-- jqueryUI -->
<script type="text/javascript" th:src="@{/resources/js/share/jquery-ui-1.12.1.custom/external/jquery/jquery.js}"></script>
<link th:href="@{/resources/js/share/jquery-ui-1.12.1.custom/jquery-ui.css}" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var rootPath = "/{项目名}";
</script>
</th:block>
homepage.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>主页</title>
<th:block th:replace="common/base/initHead :: #initHead"></th:block><!-- 调用模板 -->
<script language="javascript">
$(function() {});
</script>
</head>
<body class="homepage_body">....
common/base/initHead :: #initHead"></th:block><!-- 调用模板 -->
<script language="javascript">
$(function() {});
</script>
</head>
<body class="homepage_body">....
问题来了,我们如何找到initHead.html文件呢?
其实也是通过配置的thymeleaf路径下查找。例如我配置了
<