Thymeleaf之HTML分模块

模块制作:

使用th:block th:fragment="模块名"

common_css导入css样式:

<html xmlns:th="http://www.thymeleaf.org">
<!--公共css-->
<th:block th:fragment="common_css">
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="/backstage/plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/backstage/plugins/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/backstage/plugins/ionicons/css/ionicons.min.css">
    <link rel="stylesheet" href="/backstage/plugins/iCheck/square/blue.css">
    <link rel="stylesheet" href="/backstage/plugins/morris/morris.css">
    <link rel="stylesheet" href="/backstage/plugins/jvectormap/jquery-jvectormap-1.2.2.css">
</th:block>
<!--公共CSS-->

common_header侧边栏:

<html xmlns:th="http://www.thymeleaf.org">
<!-- 页面头部 -->
<header class="main-header" th:fragment="header">
    <!-- Logo -->
    <a href="/backstage/index" class="logo">
        <span class="logo-mini"><b>后台</b></span>
        <span class="logo-lg">数据<b>后台</b>管理</span>
    </a>
    <!--导航右边头像-->
    <nav class="navbar navbar-static-top">
    </nav>
    <!--导航右边头像-->
</header>
<!-- 页面头部 -->

将公用的模块进行组合:

 使用th:replace="文件路径::模块名"

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>新增产品类型</title>
    <th:block th:replace="/backstage/common/common_resources::common_css"/>
</head>
<body class="hold-transition skin-purple sidebar-mini">
<div class="wrapper">
    <!-- 页面头部 -->
    <header th:replace="/backstage/common/common_header::header"></header>
</div>
</body>
</html>



th:insert 是最简单的,它将目标标签作为自己本地标签的子标签插入进来,带目标标签的属性。

th:replace 直接把本地标签换成了目标标签,带属性。

th:include 只是将目标标签的内容(例如它的子标签)插入到本地标签来,不带属性。th:include 属性在 Thymeleaf 3.0之后就不推荐使用了


<div th:insert="~{menu :: menu-copy}"></div>

结果:

<div>
    <menu th:fragment="menu-copy">
    	<p>menu</p>
    	<a href="/home2.html"
           th:href="@{/home2}">主页面2</a>
    	<a href="/subscribe"
           th:href="@{/subscribe}">订阅点这里</a>
    	<a href="/"
           th:href="@{/}">主页面</a>
  </menu>
</div>


<div th:replace="~{menu :: menu-copy}"></div>

结果:

<menu th:fragment="menu-copy">
	<p>menu</p>
    <a href="/home2.html"
       th:href="@{/home2}">主页面2</a>
    <a href="/subscribe"
       th:href="@{/subscribe}">订阅点这里</a>
    <a href="/"
       th:href="@{/}">主页面</a>
</menu>


<div th:include="~{menu :: menu-copy}"></div>

结果:

<div>
    <p>menu</p>
    <a href="/home2.html"
       th:href="@{/home2}">主页面2</a>
    <a href="/subscribe"
       th:href="@{/subscribe}">订阅点这里</a>
    <a href="/"
       th:href="@{/}">主页面</a>
</div>