thymeleaf引用公共頁面

本例采用的是Springboot+thymeleaf,因?yàn)楣岔撁鎸儆趧?dòng)態(tài)頁,因此需要放在templates目錄下(具體幾層自定義即可),我們這里做一個(gè)引用頭部、主體和底部公共信息的示例

創(chuàng)新互聯(lián)建站IDC提供業(yè)務(wù):成都西信服務(wù)器托管,成都服務(wù)器租用,成都西信服務(wù)器托管,重慶服務(wù)器租用等四川省內(nèi)主機(jī)托管與主機(jī)租用業(yè)務(wù);數(shù)據(jù)中心含:雙線機(jī)房,BGP機(jī)房,電信機(jī)房,移動(dòng)機(jī)房,聯(lián)通機(jī)房。

1. 公共信息頁面

head.html,使?th:fragment屬性來定義被包含的模版?段,以供其他模版引用或者包含,這里我們定義了頭部(admin_head(title))、主體(admin_common)、底部(admin_bottom)三個(gè)模板片段

<!DOCTYPE html>
<html>
<head th:fragment="admin_head(title)">
    <meta charset="UTF-8">
    <title th:text="${title}"></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <base th:href="${#request.getContextPath()}+'/'">
    <!-- 引用頁面css樣式 -->
    <link rel="stylesheet" th:href="@{/css/common/public.css}" media="all"/>
</head>
<body>
<th:block th:fragment="admin_common">
這是公共信息
</th:block>
<th:block th:fragment="admin_bottom">
    <!-- jquery控件 -->
    <script type="text/javascript" charset="utf-8" th:src="@{/js/common/jquery-3.4.1.min.js}"></script>
</th:block>
</body>
</html>

2. 引用定義好的模板片段

2.1 示例1

main.html,雙冒號(::)前面是公共頁面路徑,不受當(dāng)前頁面層級影響,直接從根路徑寫即可

<!DOCTYPE html>
<html>
<!-- 引用公共頁面頭部片段信息,雙冒號(::)前后都要有空格,切記 -->
<head th:replace="common/head :: admin_head(測試頁)">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<!-- 引用公共頁面主體片段信息 -->
<body th:include="common/head :: admin_common">

</body>
</html>

我們來看一下頁面源碼,頭部信息和主體都已經(jīng)加載過來了

thymeleaf引用公共頁面

2.2 示例2

list.html,雙冒號(::)前面是公共頁面路徑,不受當(dāng)前頁面層級影響,直接從根路徑寫即可

<!DOCTYPE html>
<html>
<!-- 引用公共頁面頭部片段信息,雙冒號(::)前后都要有空格,切記 -->
<head th:replace="common/head :: admin_head(user列表)"></head>
<body>
    OK
    <!-- 引用公共頁面底部片段信息 -->
    <th:block th:replace="common/head :: admin_bottom"></th:block>
</body>
</html>

我們來看一下頁面源碼,頭部信息和主體都已經(jīng)加載過來了

thymeleaf引用公共頁面

3. 引用說明

引用模板的時(shí)候可以使用 th:insert或者 th:replaceth:insert與th:replace 區(qū)別如下:
th:insert:將被引用的模板片段插?到自己的標(biāo)簽體中
th:replace:將被引用的模板片段替換掉自己
th:include:類似于 th:insert,?不是插??段,它只插?此?段的內(nèi)容(Thymeleaf 3.0 之后不再推薦使?)

4. 項(xiàng)目目錄結(jié)構(gòu)如下

thymeleaf引用公共頁面

5. 標(biāo)簽說明

th:block空標(biāo)簽詳解

6 源碼

移步碼云下載

新聞標(biāo)題:thymeleaf引用公共頁面
本文路徑:http://bm7419.com/article28/gipjjp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)企業(yè)網(wǎng)站制作、商城網(wǎng)站、做網(wǎng)站、手機(jī)網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計(jì)公司