ページの共通部分をテンプレート化 & HTML5 [Thymeleaf]
内容
Spring Bootで画面を作成する際に、
ベースの共通を1つに記載できる
Thymeleaf Layout Dialect をHTML5 形式で実装する。
記事やサイトのページを作る際に
共通ヘッダーやフッターは同じものを表示するので
1ヶ所の記載だけで済むので便利!
Thymeleaf Layout Dialectでテンプレートページを作成
作成したテンプレートページの画面
実装ポイント
- htmlタグに使用する名前空間「xmlns:layout」を定義
- 各ページ内容となるコンテンツ部分のdivタグに「layout:fragment=“content"」を定義
- 上記以外は自由に作成。コンテンツとページタイトル以外はこのテンプレートページとなる。
layout.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" lang="ja"> <head> <title>layout</title> <meta charset="UTF-8" /> <link rel="stylesheet" href="/jquery-ui-1.12.1.custom/jquery-ui.css" /> <link rel="stylesheet" href="/css/layout.css" /> </head> <body> <header> <span id="title">ホームページ</span><img id="hippo" src="/img/hippo.png" /> </header> <hr /> <nav> <ul> <li><a href="">メニュー1</a></li> <li><a href="">メニュー2</a></li> <li><a href="">メニュー3</a></li> </ul> <br /> </nav> <hr /> <div layout:fragment="content"> コンテント<br /> コンテント<br /> コンテント<br /> コンテント<br /> コンテント<br /> </div> <hr /> <footer> <address id="info">(C) 2017 w-hippo.com <a href="mailto:w.hippo.info@gmail.com">お問い合わせ</a></address> </footer> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="/jquery-ui-1.12.1.custom/jquery-ui.js"></script> <script> <!-- ここにGoogleAnalyticsのObjectを入れたりする --> </script> </body> </html>
layout.css
header { text-align: center; } #title { font-size: 60px; padding: 20px; vertical-align: top; } #hippo { width: 100px; } nav > ul { list-style: none; // 黒ぽち消す } nav > ul > li { float: left; margin: 0 50px; } footer { text-align: center; } footer > address#info{ font-size: 10px; }
作成したテンプレートをもとにページを作成
作成したページ
実装ポイント
- htmlタグに使用するテンプレートを定義「layout:decorator=“layout"」
- コンテンツ部分のdivタグに「layout:fragment=“content"」を定義(テンプレート一緒にする)
dialect.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="layout"> <head> <title>Dialectサンプル</title> </head> <body> <div layout:fragment="content"> <h2>Dialectを使って表示</h2> <img src="/img/hippo.png" /> </div> <hr /> </body> </html>
参考にさせて頂いたページ
Spring Boot解説第16回(開発環境編:Thymeleafその2 ~Thymeleaf Layout Dialect~) - Qiita
【爆速】HTML5 + CSS3で簡単にWebデザインしよう! - Qiita