Home
Java
타임리프 레이아웃 구조 설정 (thymeleaf-layout-dialect)
devfoxstar
devfoxstar
May 01, 2022
1 min

Table Of Contents

01
라이브러리 추가
02
레이아웃 페이지
03
공통 파일

뷰페이지 구조를 잡기 위해서는 먼저 레이아웃을 설정해야 합니다.
Thymeleaf에는 Dialect라는 간편한 라이브러리가 있습니다.


라이브러리 추가

레이아웃을 사용하기 위해 라이브러리를 추가해 줍니다.

Gradle

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

Maven

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>

레이아웃 페이지

웹페이지에서 공통으로 사용 할 레이아웃 페이지를 구성합니다.
최근 대부분의 뷰템플릿에서는 비슷한 구조를 제공합니다.

layout.html

<!DOCTYPE html>
<html 
    xmlns:th="http://www.thymeleaf.org"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <title>Layout page</title>
    <script src="common-script.js"></script>
</head>
<body>
    <header>
        <h1>My website</h1>
    </header>

    <section layout:fragment="content">
        <p>Page content goes here</p>
    </section>
</body>
</html>

개별 페이지의 layout:decorate에 작성한 레이아웃 경로를 지정해 주면 됩니다.

content.html

<!DOCTYPE html>
<html 
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
    layout:decorate="~{layout.html}">
<head>
    <title>Content page</title>
    <script src="content-script.js"></script>
</head>
<body>
    <section layout:fragment="content">
        <p>This is a paragraph from the content page</p>
    </section>
</body>
</html>

그럼 아래와 같이 합쳐진 결과 값을 얻을 수 있습니다.

<!DOCTYPE html>
<html>
<head>
    <title>Content page</title>
    <script src="common-script.js"></script>
    <script src="content-script.js"></script>
</head>
<body>
    <header>
        <h1>My website</h1>
    </header>

    <section>
        <p>This is a paragraph from the content page</p>
    </section>
</body>
</html>

공통 파일

추가로 공통 파일을 별도로 작성해서 불러올 수도 있습니다.
footer를 예제로 보겠습니다.

layout.html

<!DOCTYPE html>
<html 
    xmlns:th="http://www.thymeleaf.org"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <title>Layout page</title>
    <script src="common-script.js"></script>
</head>
<body>
    <header>
        <h1>My website</h1>
    </header>

    <section layout:fragment="content">
        <p>Page content goes here</p>
    </section>

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

footer.html 파일에 th:fragment를 지정하면 됩니다.
보통 공통 파일은 fragments 폴더에 저장합니다.

fragments/footer.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <footer th:fragment="footer">
        <p>Footer</p>
    </footer>
</html>

Thymeleaf Layout Dialect


Tags

#Java#Thymeleaf#Layout#Dialect

Related Posts

Java - Record class (불변 데이터 객체 만들기)
June 11, 2024
1 min
© 2024, All Rights Reserved.

Quick Links

About Me

Media