본문 바로가기
Spring/Spring Boot & Thymeleaf

[Spring Boot & Thymeleaf] 16. 템플릿 레이아웃

by Kloong 2022. 10. 24.

참고

더보기

Spring Boot & Thymeleaf 시리즈는 김영한 님의 "스프링 MVC 2편 - 백엔드 웹 개발 활용 기술" 강의를 정리한 글입니다. 글에 첨부된 사진은 해당 강의의 강의 자료에서 캡쳐한 것입니다. 제 Github에만 올려뒀다가, 정보 공유와 강의 홍보(?)를 위해 블로그에도 업로드합니다.

 

스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 - 인프런 | 강의

웹 애플리케이션 개발에 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. MVC 2편에서는 MVC 1편의 핵심 원리와 구조 위에 실무 웹 개발에 필요한 모든 활용 기술들을 학습할 수 있

www.inflearn.com

마크다운 형식으로 작성한 글을 블로그에 다시 올리는 거라 가독성이 많이 떨어집니다. 조금더 편하게 보시려면 아래의 Github repository에서 보시면 됩니다.

 

GitHub - Kloong1/TIL: Today I Learned.

Today I Learned. Contribute to Kloong1/TIL development by creating an account on GitHub.

github.com

타임리프 - 템플릿 레이아웃

이전에는 일부 코드 조각을 가지고 오기만 했다면, 이번에는 개념을 더 확장해서 내가 원하는 코드 조각을 레이아웃에 넘긴 다음 레이아웃을 불러와서 사용하는 방법에 대해서 알아보자.

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

단순히 문자 파라미터를 넘기는 정도가 아니라, 태그 전체를 레이아웃에 맞춰서 넘기는 작업을 할 수 있다.

템플릿 레이아웃

TemplateController.java 내용 추가
package kloong.thymeleaf.basic;

import ... //생략
@Controller
@RequestMapping("/template")
public class TemplateController {

    @GetMapping("/layout")
    public String layout() {
        return "template/layout/layoutMain";
    }
}
/resources/templates/template/layout/layoutMain.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<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>
  • <head th:replace="~{template/layout/base :: common_header(~{::title},~{::link})}">
    • 앞에서 배운 파라미터와 함께 템플릿 조각 사용하는 문법과 거의 똑같은 것 같은데, 파라미터가 조금 달라졌다.
    • template/layout/base.html 파일의 common_header 템플릿 조각을 불러와서 사용할 건데, 불러오면서 다음과 같은 내용을 전달하겠다는 의미이다.
      • ::title 은 현재 페이지의 <title> 태그들을 전달한다.
      • ::link 는 현재 페이지의 <link> 태그들을 전달한다.
/resources/templates/template/layout/base.html
<html xmlns:th="http://www.thymeleaf.org">
<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>
  • th:replace 에 의해 기존의 태그들이 전달받은 태그로 교체된다.
  • 나머지 공통 부분들은 그대로 유지된다.
실행 결과

<!DOCTYPE html>
<html>
<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>

이 방식은 사실 앞서 배운 코드 조각을 조금 더 적극적으로 사용하는 방식이다. 쉽게 이야기해서 레이아웃 개념을 두고, 그 레이아웃에 필요한 코드 조각을 전달하는 방식으로 확장하는 것이다.

템플릿 레이아웃 확장

앞서 이야기한 개념을 <head> 태그에만 적용하는게 아니라 <html> 전체에 적용할 수도 있다. 즉 태그 하나를 레이아웃으로 사용하는 것이 아니라, 파일 전체를 레이아웃으로 만들고 레이아웃에 원하는 코드 조각을 추가할 수 있다.

TemplateController.java 내용 추가
package kloong.thymeleaf.basic;

import ... //생략

@Controller
@RequestMapping("/template")
public class TemplateController {

    @GetMapping("/layoutExtend")
    public String layoutExtend() {
        return "template/layoutExtend/layoutExtendMain";
    }
}
/resources/templates/template/layoutExtend/layoutFile.html
<!DOCTYPE html>
<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>
  • /resources/templates/template/layoutExtend/layoutExtendMain.html
    <!DOCTYPE html>
    <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>
  • th:fragmentth:replace 속성이 <html> 태그에 들어가있는 것을 확인할 수 있다. 즉 <html>...</html> 사이의 특정 태그를 넘기고, 치환한다는 의미이다.
  • 같은 구조를 가진 페이지가 많아지는 경우, 페이지 구조를 수정해야 할 때 레이아웃을 사용하면 매우 편하게 유지보수를 할 수 있다.

댓글