프로그래머스/Spring Boot

[Spring Boot] Thymeleaf 템플릿 상속 (Template Inheritance)

annovation 2025. 2. 6. 08:49

템플릿 상속 (Template Inheritance)

템플릿 상속(Template Inheritance)은 웹 페이지의 공통적인 구조를 정의한 뒤, 이를 기반으로 다른 페이지들이 해당 구조를 재사용하도록 하는 기법입니다.

 

ex. 웹사이트의 공통 구조

  • 헤더(Header) : 로고, 네비게이션 메뉴 등 상단에 항상 표시되는 영역
  • 본문(Main Content) : 페이지마다 내용이 달라지는 영역
  • 푸터(Footer) : 저작권 표시, 연락처 등 하단에 항상 표시되는 영역

이 공통 구조를 매 페이지마다 반복해서 작성하면 번거롭고 비효율적입니다. 템플릿 상속은 이러한 문제를 해결하기 위해 사용됩니다.


작동 방식

1. th:replace

Thymeleaf에서 템플릿 상속을 구현할 때, 하위 템플릿이 공통 템플릿의 특정 부분을 교체할 수 있도록 돕는 속성입니다. 이 속성을 사용하면 원하는 위치에 다른 템플릿의 내용을 삽입할 수 있습니다.

 

2. th:fragment

Thymeleaf의 Fragment(조각)는 HTML 코드의 재사용 가능한 블록을 정의합니다. 템플릿 상속에서 이 조각들은 특정 페이지에서 채워지거나 덮어씌워질 수 있습니다.


예시

1. 공통 구조 정의

웹사이트의 공통적인 구조를 먼저 정의합니다. 이를 기본 템플릿이라고 합니다.

  • layout.html
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:insert="~{::title}">Default Title</title>
    <link rel="stylesheet" th:href="@{/styles.css}">
</head>
<body>
    <header>
        <h1>My Website</h1>
        <nav>
            <a href="/">홈</a>
            <a href="/questions">질문 목록</a>
        </nav>
    </header>
    
    <main>
        <div th:insert="~{::content}"></div>
    </main>
    
    <footer>
        <p>&copy; 2024 My Website</p>
    </footer>
</body>
</html>
  • th:insert : 제목(title)과 본문(content)을 다른 템플릿에서 채울 수 있도록 정의

2. 질문 목록 페이지 작성

  • questionList.html
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org" th:replace="layout :: layout">
<head>
    <title>질문 목록</title>
</head>
<body>
    <div th:fragment="content">
        <h2>질문 목록</h2>
        <ul>
            <li th:each="question : ${questions}" th:text="${question.subject}"></li>
        </ul>
    </div>
</body>
</html>
  • th:replace : layout.html의 공통 구조를 상속
  • th:fragment : 질문 목록 내용을 layout.html content에 삽입

3. 질문 상세 페이지 작성

  • questionList.html
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org" th:replace="layout :: layout">
<head>
    <title>질문 상세</title>
</head>
<body>
    <div th:fragment="content">
        <h2 th:text="${question.subject}"></h2>
        <p th:text="${question.content}"></p>
        <a href="/questions">질문 목록으로 돌아가기</a>
    </div>
</body>
</html>

출처

OpenAI ChatGPT (https://openai.com)

'프로그래머스 > Spring Boot' 카테고리의 다른 글

[Spring Boot] Generic  (0) 2025.03.10
[Spring Boot] JpaRepository Optional  (1) 2025.03.02
[Spring Boot] PRG 패턴  (0) 2024.12.20
[Spring Boot] DTO(Data Transfer Object)  (0) 2024.12.17
[Spring Boot] Thymeleaf 속성  (0) 2024.12.16