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

烦恼

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

建立common

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

11.png

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>

非特殊说明,本博所有文章均为博主原创。

如若转载,请注明出处:http://www.notemi.cn/thymeleafs-include-encapsulated-common-pages-js-and-css.html

添加新评论

icon_question.pngicon_razz.pngicon_sad.pngicon_evil.pngicon_exclaim.pngicon_smile.pngicon_redface.pngicon_biggrin.pngicon_surprised.pngicon_eek.pngicon_confused.pngicon_cool.pngicon_lol.pngicon_mad.pngicon_twisted.pngicon_rolleyes.pngicon_wink.pngicon_idea.pngicon_arrow.pngicon_neutral.pngicon_cry.pngicon_mrgreen.png

11 + 7 =


已有 3 条评论
    啦啦啦 啦啦啦
    Aug 31, 2018 回复

    这个似乎会有两个head元素 ,可以用th:replace替换head...


    Feb 2, 2018 回复

    很好的文章,谢谢博主。 icon_lol.png

      Feb 2, 2018 回复

      不用。