基于 Spring Boot 博客系统开发(三)

发布于:2024-04-28 ⋅ 阅读:(15) ⋅ 点赞:(0)

基于 Spring Boot 博客系统开发(三)

本系统是简易的个人博客系统开发,为了更加熟练地掌握 SprIng Boot 框架及相关技术的使用。🌿🌿🌿
基于 Spring Boot 博客系统开发(二)👈👈

thymeleaf 抽取公共页面

在Thymeleaf中,如果你想要抽取公共页面(例如,头部、底部、导航栏等),可以通过定义和使用片段(fragments)和包含(includes)来实现。

首页head部分的公共代码抽取成碎片,使用 thymeleaf 的标签 th:fragment 和 th:include
原代码

<head>
    <title>首页</title>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"/>
    <meta name="renderer" content="webkit"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-transform"/>
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="shortcut icon" href="./user/img/bloglogo.jpg"/>
    <link rel="apple-touch-icon" href="./user/img/apple-touch-icon.png"/>
    <link href="./user/css/xcode.min.css" rel="stylesheet"/>
    <link href="./user/css/style.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="./assets/css/amazeui.min.css"/>
    <link rel="stylesheet" href="./assets/css/app.css"/>
    <script src="./assets/js/jquery.min.js"></script>
    <script src="./assets/js/amazeui.min.js"></script>
    <!--[if lt IE 9]>
    <script src="/back/js/html5shiv.js"></script>
    <script src="/back/js/respond.min.js"></script>
    <![endif]-->
</head>

首先,在client目录下创建include.html文件,include.html 文件代码:

<div th:fragment="common-css" >
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"/>
    <meta name="renderer" content="webkit"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-transform"/>
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="shortcut icon" href="./user/img/bloglogo.jpg"/>
    <link rel="apple-touch-icon" href="./user/img/apple-touch-icon.png"/>
    <link href="./user/css/xcode.min.css" rel="stylesheet"/>
    <link href="./user/css/style.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="./assets/css/amazeui.min.css"/>
    <link rel="stylesheet" href="./assets/css/app.css"/>
</div>

<div th:fragment="common-js" >
    <script src="./assets/js/jquery.min.js"></script>
    <script src="./assets/js/amazeui.min.js"></script>
    <!--[if lt IE 9]>
    <script src="/back/js/html5shiv.js"></script>
    <script src="/back/js/respond.min.js"></script>
    <![endif]-->
</div>

然后,在你的主页面(比如index.html)中,使用Thymeleaf的th:include来复用这段代码。
整理后的代码:

<head>
    <title>首页</title>
    <th:block th:include="client/include :: common-css" />
    <th:block th:include="client/include :: common-js" />
</head>

将需要抽取的代码放到include fragment中,需要用到这些代码的地方使用th:include引用。

代码整理后效果

首页
在这里插入图片描述
文章详情页
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到