본문 바로가기
카테고리 없음

스프링 부트(SpringBoot) 상단 하단 메뉴 구성(Layout Dialect, Tiles)

by redbear0077 2025. 2. 2.
반응형

스프링 부트(SpringBoot) 상단 하단 메뉴 구성(Layout Dialect, Tiles)

 

환경

자바8
인텔리제이
스프링부트
마리아 디비
그레이들(gradle)
타임리프(thymeleaf)
application.properties

 

그레이들(gradle) 설정
dependencies {
    .
    .
    .
    .
    //thymeleaf
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
    .
    .
    .
    .
}

 

화면 생성
  • default.html생성
src/main/resources/templates/layout/default.html
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <meta charset="UTF-8">
    <title layout:title-pattern="$CONTENT_TITLE - MyApp">MyApp</title>
</head>
<body>
    <header th:replace="~{fragments/header :: header}"></header>

    <main layout:fragment="content">
        <!-- 개별 페이지의 내용이 여기에 들어감 -->
    </main>

    <footer th:replace="~{fragments/footer :: footer}"></footer>
</body>
</html>

 

  • header.html생성
src/main/resources/templates/fragments/header.html
<header th:fragment="header">
    <h1>MyApp</h1>
    <nav>
        <a href="/">홈</a>
        <a href="/about">소개</a>
    </nav>
</header>

 

  • footer.html
src/main/resources/templates/fragments/footer.html

 

<footer th:fragment="footer">
    <p>&copy; 2025 MyApp</p>
</footer>

 

  • home.html
src/main/resources/templates/home.html


layout:decorate="~{layout/default}" → default.html 을 상속

<main layout:fragment="content"> → default.html 의 <main> 부분에 삽입된다
<!DOCTYPE html>
<html lang="ko" layout:decorate="~{layout/default}">
<head>
    <title>홈</title>
</head>
<body>
    <main layout:fragment="content">
        <h2>홈 페이지</h2>
        <p>환영합니다!</p>
    </main>
</body>
</html>

 

  • about.html
src/main/resources/templates/about.html
<!DOCTYPE html>
<html lang="ko" layout:decorate="~{layout/default}">
<head>
    <title>소개</title>
</head>
<body>
    <main layout:fragment="content">
        <h2>소개 페이지</h2>
        <p>이 앱은 Spring Boot + Thymeleaf로 만들어졌습니다.</p>
    </main>
</body>
</html>

 

컨트롤러(Controller) 설정
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class PageController {

    @GetMapping("/")
    public String home() {
        return "home";
    }

    @GetMapping("/about")
    public String about() {
        return "about";
    }
}

 

실행결과 및 URL
URL 화면
http://localhost:8080/ home.html이 default.html을 상속하여 렌더링된다.
http://localhost:8080/about about.html이 default.html을 상속하여 엔더링된다.
반응형