目录

烦恼

一个项目中,总会有很多重复的东西出现,比如css,js,网页头部底部,重复性的东西我觉得都应该优化。今天我们就讲讲Thymeleaf使用 th:fragment 来将重复的东西抽出,使用 th:include 来引入。

建立common

首先我们建立一个公用的common文件夹,里面存放公共的html文件。

Thymeleaf的include封装共用页面,js和css

head.html里面就存放公用的标签

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:fragment = "commonHead(title)">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title th:text="${title}">Title</title>
    <meta name="description" content="">
    <meta name="keywords" content="index">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <link rel="icon" type="image/png" href="assets/i/favicon.png">
    <link rel="apple-touch-icon-precomposed" href="assets/i/app-icon72x72@2x.png">
    <meta name="apple-mobile-web-app-title" content="Amaze UI" />
    <link rel="stylesheet" href="/css/amazeui.min.css" />
    <link rel="stylesheet" href="/admin/css/admin.css">
    <link rel="stylesheet" href="/admin/css/app.css">
</head>
</html>

on-load-js.html里面就存放公用的js

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<span th:fragment="commonOnLoadJs">
    <script src="/admin/js/echarts.min.js"></script>
    <script src="/js/jquery.min.js"></script>
    <script src="/js/amazeui.min.js"></script>
    <script src="/admin/js/iscroll.js"></script>
    <script src="/admin/js/app.js"></script>
    <script src="/js/layer/layer.js"></script>
</span>
</html>

引入common

引入head,就在其它页面这样引入。

<head th:include="/admin/common/head :: commonHead('后台首页')"></head>

引入js

<span th:include="/admin/common/on-load-js :: commonOnLoadJs"></span>