thymeleaf layout


 
 
thymeleaf的layout常用的有兩種方式用法
第一種
將頁面里的每個部分都分成 塊 -> fragment 使用 th:include 和 th:replace 來引入頁面
這種用法沒有layout的概念, 因為每個部分都是 fragment, 下面例子說明
<!-- index.html -->
<html>
<head>
    <meta charset="utf-8"/>
    <title>demo</title>
</head>
<body>
    <div th:include="components/header :: header"></div>
    <div class="container">
        <h1>hello world</h1>
    </div>
    <div th:include="components/footer :: footer"></div>
</body>
</html>

<!-- components/header.html -->
<header th:fragment="header">
<ul>
    <li>news</li>
    <li>blog</li>
    <li>post</li>
</ul>
</header>
<!-- components/footer.html -->
<header th:fragment="footer">
<div>i am footer.</div>
</header>
上面例子里用到的是th:include, 也就是把定義好的fragment引入的意思, 還有一個是th:replace, 意思是替換當前頁面里的這部分代碼, 下面例子說明一下
<html>
<head>
    <meta charset="utf-8"/>
    <title>demo</title>
</head>
<body>
    <div th:replace="components/header :: header">
        <!-- 使用th:replace進來的header.html會替換下面的這個header -->
        <header>
            <ul>
                <li>static - news</li>
                <li>static - blog</li>
                <li>static - post</li>
            </ul>
        </header>
    </div>
    <div class="container">
        <h1>hello world</h1>
    </div>
    <div th:include="components/footer :: footer"></div>
</body>
</html>
第二種
寫一個layout.html頁面,當作頁面的基礎頁面
<!-- layout/layout.html -->
<html>
<head>
    <meta charset="utf-8"/>
    <title>demo</title>
</head>
<body>
    <div th:include="components/header :: header"></div>
    <div layout:fragment="content"></div>
    <div th:include="components/footer :: footer"></div>
</body>
</html>
在子頁面里使用 layout:decorator 來將子頁面里的內容加入到 layout.html里去
<!-- index.html -->
<html layout:decorator="layout/layout">
<head>...</head>
<body>
    <div layout:fragment="content">
        <h2>hello world!!!</h2>
    </div>
</body>
</html>
這樣在layout.html里引入的css,js,imgs都可以在子頁面里用了,而且在子頁面里還可以引入子頁面需要用到的css,js,imgs, 就很方便了 推薦
模板傳值,假如要往header.html里傳入一個tab來區別應該高亮哪個菜單,可以使用下面的寫法實現, 先定一個樣式
 .active {background-color: green;}
<header th:fragment="header (tab)">
<ul>
    <li>
        <span th:class="${tab eq 'news'} ? active">news</span>
    </li>
    <li>
        <span th:class="${tab eq 'blog'} ? active">blog</span>
    </li>
    <li>
        <span th:class="${tab eq 'post'} ? active">post</span>
    </li>
</ul>
</header>
調用寫法
<div th:include="components/header :: header(tab='blog')"></div>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM