Spring Boot Layout을 위한 패키지를 추가하여 마스터 페이지를 만드는 방법을 알아봅니다.

 

pom.xml

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>nz.net.ultraq.thymeleaf</groupId>
			<artifactId>thymeleaf-layout-dialect</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

 

/templates/shared/_layout.html

<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>헤더</h1>
    <div layout:fragment="content">
        <p>Changing contents</p>
    </div>
    <h1>푸터</h1>
</body>
</html>

 

/templates/index.html

<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="shared/_layout">

<body>

    <div layout:fragment="content">

        내용만 들어오는 곳

    </div>

</body>

</html>

 

HomeController.java

package com.hawaso.javacampus;

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

@Controller
//@RequestMapping("/")
public class HomeController {
    @GetMapping("/")
    public String index() {
        return "index";
    }
}

 

실행 결과:

JavaCampus_Layout.png

 

 

자바스크립트 포함:

_layout.html

<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>헤더</h1>
    <div layout:fragment="content">
        <p>Changing contents</p>
    </div>
    <h1>푸터</h1>

    <th:block layout:fragment="script"></th:block>
</body>
</html>

 

index.html

<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="shared/_layout">
<body>
    <div layout:fragment="content">
        내용만 들어오는 곳
    </div>

    <th:block layout:fragment="script">
        <script th:src="@{/js/site.js}"></script>
    </th:block>
</body>
</html>

 

실행 소스:

JavaCampus_Layout_Source.png

 

 

Comments

Be the first to post a comment

Post a comment