LoginSignup
1
0

More than 1 year has passed since last update.

SpringBootにおけるレイアウト

Last updated at Posted at 2021-07-30

本日の内容

  • レイアウト機能を用いて画面を構成するため必要な知識の備忘録
  • Thymeleafのレイアウト機能を用いて完成させる
  • 共通レイアウトとしてヘッダー、フッター、サイドバーを用意し、個別画面の内容を出力する
  • レイアウト機能を利用した画面は保守性、拡張性に優れている

画面イメージ

image.png

レイアウト画面について

  • レイアウトのhtmlにレイアウトとして使用するという宣言をする
  • ヘッダー、フッター、サイドバー、コンテンツのスペースを確保するイメージ
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:fragment="layout(body)">
<head>
<meta charset="UTF-8">
<link th:href="@{/css/layout.css}" rel="stylesheet">
<title>Insert title here</title>
</head>
<body>
    <div th:replace="~{header::layout-header}"></div>
    <div>
        <div th:replace="~{sidebar::layout-sidebar}"></div>
        <div id="main" th:replace="${body}"></div>
    </div>
    <div th:replace="~{footer::layout-footer}"></div>
</body>
</html>

テンプレートを実装するにあたって

  • th:fragment属性を記述→このHTMLをテンプレートとして使用するという宣言
  • fragment(フラグメント)→そのデータを識別する名前
  • th:fragment="layout(body)"→layoutという名前を付けて、そのテンプレートに個別画面のbodyの内容を埋め込む
  • th:replace属性→共通部品の埋め込み先となるタグを記述する
  • <タグ名 th:replace=~{ファイルのパス名 :: フラグメント名}">で記述
  • ファイルのパス名→templatesフォルダを起点としたファイル名(拡張子は除く)
  • フラグメント名にはth:fragmentで設定した名前を記述
  • コンテンツ画面を埋め込む場所にはth:replace="${取得する情報の範囲}"
  • 共通部品(ヘッダー、フッター、サイドバー)にそれぞれ名前をつける

    ヘッダー

    <div id="header" th:fragment="layout-header">ヘッダー</div>
    

    フッター

    <div id="footer" th:fragment="layout-footer">フッター</div>
    

    サイドバー

    <div id="sidebar" th:fragment="layout-sidebar">サイドバー</div>
    

    コンテンツ画面(テンプレートのメインに埋め込む画面)

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org"
        th:replace="~{layout::layout(~{::body/content()})}">
    <head>
    <meta charset="UTF-8">
    <link th:href="@{/css/layout.css}" rel="stylesheet">
    <title>Insert title here</title>
    </head>
    <body id="main">
        <div>コンテンツ内容</div>
    </body>
    </html>
    
    • コンテンツ画面にはth:replace="~{テンプレートのパス::フラグメント名(~{::コンテンツ画面から取得される情報の範囲})}"のように記載をする
    • th:replace="~{layout::layout(~{::body/content()})}"→layout.htmlに対して、コンテンツ画面(index.html)のbodyタグの内容を埋め込んでいる
    • bodyの後の/content()はbodyタグ内のコンテンツを取得するという意味

    装飾

    div#header {
        background-color: red;
        height: 100px;
    }
    
    div#sidebar {
        background-color: yellow;
        float: left;
        height: 300px;
        width: 200px;
    }
    
    div#main {
        float: left;
        height: 300px;
    }
    
    div#footer {
        background-color: green;
        clear: left;
        height: 100px;
    }
    

    ふりかえり

    • thymeleafの機能を利用すれば比較的観点にレイアウト機能を実装できる
    • 一度レイアウトの枠組みを作ってしまえば、あとは個別のコンテンツ画面を作るだけでいいので、ページ作成の効率化になる
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0