Java Category/Thymeleaf

[Thymeleaf] 타임리프 레이아웃

ReBugs 2024. 3. 8.

이 글은 인프런 김영한님의 Spring 강의를 바탕으로 개인적인 정리를 위해 작성한 글입니다.


타임리프(Thymeleaf)에서 템플릿 레이아웃은 웹 애플리케이션의 다양한 페이지에서 공통적으로 사용되는 레이아웃 구조를 재사용할 수 있도록 도와준다.

이를 통해 개발자는 중복 코드를 줄이고, 일관된 레이아웃을 유지할 수 있다.

 

예를 들어서 <head> 에 공통으로 사용하는 css , javascript 같은 정보들이 있는데, 이러한 공통 정보들을 한 곳 에 모아두고, 공통으로 사용하지만, 각 페이지마다 필요한 정보를 더 추가해서 사용하고 싶다면 다음과 같이 사용하면 된다.

 

컨트롤러

@GetMapping("/layout")
public String layout() {
    return "template/layout/layoutMain";
}

 

base.html

<html xmlns:th="http://www.thymeleaf.org">

<!-- common_header 를 호출해서 이 페이지의 title 태그와 link 태그를 대체함 -->
<!-- title 과 links 는 단순 파라미터 이름 -->
<head th:fragment="common_header(title,links)">
    <title th:replace="${title}">레이아웃 타이틀</title>

    <!-- 공통 -->
    <link rel="stylesheet" type="text/css" media="all" th:href="@{/css/awesomeapp.css}">
    <link rel="shortcut icon" th:href="@{/images/favicon.ico}">
    <script type="text/javascript" th:src="@{/sh/scripts/codebase.js}"></script>

    <!-- 추가 -->
    <th:block th:replace="${links}" />
</head>

 

layoutExtend.html

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

    <!-- base.html로 common_header 라는 이름으로 타이틀과 링크 태그를 파라미터로 넘김 -->
    <!-- 타이틀 태그와 링크 태그를 파라미터로 넘길 수 있음 -->
    <head th:replace="template/layout/base :: common_header(~{::title},~{::link})">
        <title>메인 타이틀</title>
        <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
        <link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">
    </head>
    <body> 메인 컨텐츠 </body>
</html>

common_header(~{::title},~{::link}) 이 부분이 핵심이다.

  • ::title 은 현재 페이지의 title 태그들을 전달한다.
  • ::link 는 현재 페이지의 link 태그들을 전달한다.

 

결과

<!DOCTYPE html>
<html>

    <!-- base.html로 common_header 라는 이름으로 타이틀과 링크 태그를 파라미터로 넘김 -->
    <!-- 타이틀 태그와 링크 태그를 파라미터로 넘길 수 있음 -->
    <head>
        <title>메인 타이틀</title>

        <!-- 공통 -->
        <link rel="stylesheet" type="text/css" media="all" href="/css/awesomeapp.css">
        <link rel="shortcut icon" href="/images/favicon.ico">
        <script type="text/javascript" src="/sh/scripts/codebase.js"></script>

        <!-- 추가 -->
        <link rel="stylesheet" href="/css/bootstrap.min.css"><link rel="stylesheet" href="/themes/smoothness/jquery-ui.css">
	</head>
    <body> 메인 컨텐츠 </body>
</html>

메인 타이틀이 전달한 부분으로 교체되었다.

공통 부분은 그대로 유지되고, 추가 부분에 전달한 <link> 들이 포함된 것을 확인할 수 있다.

 

<head> 정도에만 적용하는게 아니라 <html> 전체에 적용할 수도 있다.

컨트롤러

@GetMapping("/layoutExtend")
public String layoutExtends() {
    return "template/layoutExtend/layoutExtendMain";
}

 

layoutFile.html

<!DOCTYPE html>
<!-- layout 을 호출해서 이 페이지의 title 태그와 div 태그를 대체함 -->
<!-- title->title, div->section 으로 대체 -->
<!-- title 과 content 는 단순 파라미터 이름 -->
<html th:fragment="layout (title, content)" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title th:replace="${title}">레이아웃 타이틀</title>
    </head>
    <body>
        <h1>레이아웃 H1</h1>
        <div th:replace="${content}">
            <p>레이아웃 컨텐츠</p>
        </div>
        <footer> 레이아웃 푸터 </footer>
    </body>
</html>

 

layoutExtendMain.html

<!DOCTYPE html>
<!-- layoutFile.html로 layout 라는 이름으로 타이틀과 섹션 태그를 파라미터로 넘김 -->
<!-- 타이틀 태그와 섹션 태그를 파라미터로 넘길 수 있음 -->
<html th:replace="~{template/layoutExtend/layoutFile :: layout(~{::title},~{::section})}" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>메인 페이지 타이틀</title>
    </head>
    <body>
        <section>
            <p>메인 페이지 컨텐츠</p>
            <div>메인 페이지 포함 내용</div>
        </section>
    </body>
</html>

 

결과

<!DOCTYPE html>
<!-- layoutFile.html로 layout 라는 이름으로 타이틀과 섹션 태그를 파라미터로 넘김 -->
<!-- 타이틀 태그와 섹션 태그를 파라미터로 넘길 수 있음 -->
<html>
    <head>
        <title>메인 페이지 타이틀</title>
    </head>
    <body>
        <h1>레이아웃 H1</h1>
        <section>
            <p>메인 페이지 컨텐츠</p>
            <div>메인 페이지 포함 내용</div>
        </section>
        <footer> 레이아웃 푸터 </footer>
    </body>
</html>

댓글