6
3

More than 1 year has passed since last update.

Spring BootにThymeleaf Layout Dialectを使う

Posted at

一つのウェブ画面にはヘッダー、フッターなど共通で使っているところがあります。
それらが画面ごとに書かれていて、ヘッダーを修正する場合、全ての画面を触らなあかんですね。
そんな面倒くさい作業を避けるために、Thymeleaf Layout Dialectを使って画面レイアウトの共通化をやってみます!

イメージ図

image.png

build.gradleにThymeleaf Layout Dialectの依存関係を追加

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf:2.6.2'
	implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:2.5.3'
}

Thymeleaf Layout Dialectの他のバージョンはここで確認

レイアウト設定

beanの登録

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import nz.net.ultraq.thymeleaf.LayoutDialect;

@Configuration
public class LayOutConfig {
	
	// thymeleaf layout
	@Bean
	public LayoutDialect layoutDialect() {
	    return new LayoutDialect();
	}
}

layout-dialectを使うためにはbeanの登録が必要です。

ディレクトリ構成

templates
	ㄴfragments
	|	ㄴconfig.html
	|	ㄴfooter.html
    |	ㄴheader.html
    ㄴlayout
	|	ㄴlayout.html
	ㄴindex.html

*フォルダ名やファイル名はご自由につけてください。その場合、layout.htmlで各fragmentのパスを書くときに注意してください。

config.html

<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
    <th:block th:fragment="config">
        <head>
            <!-- メタデータ、共通で使用するcssやjsファイルなどを宣言 -->
        </head>
    </th:block>
</html>

th:fragment=""にfragment名を書きます。

header.html

<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
  <th:block th:fragment="header">
    <!-- ヘッダーの内容を記入 -->
  </th:block>
</html>

footer.html

<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
  <th:block th:fragment="footer">
    <!-- フッターの内容を記入 -->
  </th:block>
</html>

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="~{layout/layout}">
  <th:block layout:fragment="content">
    <!-- メイン内容を記入 -->
  </th:block>  
</html>

layout:decorator="~{layout/layout}":layout.htmlのパス(.htmlは省略)

layout.html

<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
  <th:block th:replace="fragments/config :: config"></th:block>
  <body>
    <div>
      <th:block th:replace="fragments/header :: header"></th:block>
      <th:block layout:fragment="content"></th:block>
      <th:block th:replace="fragments/footer :: footer"></th:block>
    </div>
  </body>
</html>

<th:block th:replace="fragmentのパス(.htmlは省略) :: fragment名"></th:block>
<th:block layout:fragment="メイン内容のfragment名"></th:block>

結果画面

image.png

おわり

詳細のコードはここをクリック

6
3
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
6
3