目录
  • 1. 需求描述
  • 2. 使用 thymeleaf 抽取公共页面方法
  • 3. insert与replace及include抽取公共页面的区别

1. 需求描述

我们有这样一个页面,其具有左侧导航和上侧导航,在切换不同内容过程中,左侧导航和上册导航不变,也就是说我们想将左侧导航和上侧导航这个公共部分抽取出来。

注意:使用 thymeleft 必须引入 <html lang="en" xmlns:th="http://www.thymeleaf.org">

2. 使用 thymeleaf 抽取公共页面方法

利用 thymeleaf 的 insert、replace 及 include 方法。

首先创建一公共页面 html,叫做 common.html,把公共的内容放进去。并通过 id="leftmenu"th:fragment="headermenu" 标注需要抽取的内容。

方法一 id="leftmenu"

<!-- left side start-->
<div id="leftmenu" class="left-side sticky-left-side"> 内容 </div>
<!-- left side end-->

方法二th:fragment="headermenu"

<!-- header section start-->
<div th:fragment="headermenu" class="header-section">内容 </div>
<!-- header section end-->

在需要引入的位置,通过insert、replace 及 include 方法引入 引入 id="leftmenu" 标识的公共部分 (要加 # 号):

<div th:replace="common :: #leftmenu"></div>

引入通过 th:fragment="headermenu" 标识的公共部分:

<div th:replace="common :: commonheader"> </div>

3. insert与replace及include抽取公共页面的区别

  • insert: 保留原来大标签,也保留引入部分的标签
  • replace: 保留原来的大标签,不保留引入部分的标签
  • include: 不保留原来的大标签,保留引入部分的标签

以插入下列 commonheader 为例:

commonheader 在 common.html 的 header 中,是每个页面都要引入的 css 及 js 文件

<head th:fragment="commonheader">
    <!--common-->
    <link href="https://www.freexyz.cn/dev/css/style.css" rel="external nofollow"  th:href="https://www.freexyz.cn/dev/@{/css/style.css}" rel="external nofollow"  rel="stylesheet">
    <link href="https://www.freexyz.cn/dev/css/style-responsive.css" rel="external nofollow"   th:href="https://www.freexyz.cn/dev/@{/css/style-responsive.css}" rel="external nofollow"  rel="stylesheet">
    <script src="https://www.freexyz.cn/dev/js/html5shiv.js" th:src="https://www.freexyz.cn/dev/@{/js/html5shiv.js}"></script>
    <script src="https://www.freexyz.cn/dev/js/respond.min.js"th:src="https://www.freexyz.cn/dev/@{/js/respond.min.js}" ></script>
</head>

1. 使用 include

<div th:include="common :: commonheader"> </div>

结果引入部分无大标签 header(检查页面源代码功能),但是 div 还在:

SpringBoot公共页面抽取方法实现过程介绍

2. 使用 replace:

<div th:replace="common :: commonheader"> </div>

结果引入部分含大标签 header,浏览器语法检测处理掉了,但是没有 div(检查页面源代码功能):

SpringBoot公共页面抽取方法实现过程介绍

2. 使用 insert:

<div th:insert="common :: commonheader"> </div>

结果引入部分含大标签 header,也含 div(检查页面源代码功能):

SpringBoot公共页面抽取方法实现过程介绍

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。