LoginSignup
0
0

More than 1 year has passed since last update.

Spring Bootで共通レイアウトを作成

Posted at

はじめに

Spring Bootを使ってWEBページを作成する際、ヘッダー/フッターを読み込むhtmlは共通したものを使いたいと思いました。
今回はthymeleaf-layout-dialectを使っていきますが、なかなか画面に反映させるのに手間取ってしまったので、そのメモ書きです。

ディレクトリ構成

java
└─ com.example.demo
    └─ ServletInitializer.java
       TestApplication.java
       BaseLayOutConfig.java
       LayoutController.java

resources
└─ templates
     └─ layout
         └─ layout.html
            content.html

build.gradleの修正

build.gradleに以下を追記します

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:3.1.0' ★追記

今回はthymeleaf-layout-dialectの3.1.0を使用します。

BaseLayOutConfig.javaの作成

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import nz.net.ultraq.thymeleaf.layoutdialect.LayoutDialect;

@Configuration
public class BaseLayOutConfig {
	
	@Bean
	public LayoutDialect layoutDialect() {
	    return new LayoutDialect();
	}
}

thymeleaf-layout-dialectを使用するにBeanの設定が必要です。
※クラス名やメソッド名は任意です。

layout.htmlの作成

<!doctype html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
    <head>
        <meta charset="UTF-8" />
        <title>Base Layout</title>
    </head>
    <body>
        <h1>BaseLayoutです!</h1>
        <div layout:fragment="content">
        </div>
    </body>
</html>

共通レイアウト側のhtmlです。
layout:fragment="content"と記述しているところに、contnt.htnmlが入ります。

content.htmlの作成

<!doctype html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/layout}">
    <body>
        <div layout:fragment="content">
            Contentです!
        </div>
    </body>
</html>

こちらが呼び出される側のhtmlです。
layout:decorate="~{layout/layout}"で、共通レイアウトファイルを指定します。
layout:fragment="content"と記述することで、共通レイアウトが適用されます。

LayoutController.javaの作成

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class LayoutController {

    @GetMapping("/layout")
    public String method() {
        return "layout/content";
    }
}

http://localhost:8080/layout にアクセスすることで、先ほど作成したhtmlが表示されるようにします。
ここまで作成したら、上記にアクセスし、画面表示されればOKです。

0
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
0
0