Thymeleaf에서 thymeleaf-layout-dialect 소개

주의

이 문건은 과거 Hexo 블로그 (2018-02-17) 에서 이동된 문서입니다.

시간이 지남에 따라 최신 기술과 다를 수 있으니 주의 바랍니다.



Thymeleaf에서 페이지 레이아웃을 도와주는…

Spring boot로 개발을 하면 화면단 작업을 할 때 템플릿 엔진을 사용하게 됩니다.
Freemaker, JSP, Thymeleaf와 같은 텍스트 템플릿 엔진을 사용하거나 TilesSitemesh와 같은 레이아웃 템플릿 엔진을 함께 사용하여 화면단 개발을 하게 됩니다.

이중 Thymeleaf에서는 공통적으로 사용하는 레이아웃을 작성하기 위해서는 thymeleaf-layout-dialect를 사용하면 좋습니다.

Thymeleaf Layout Dialect Github 페이지의 소개글을 간략하게 번역하자면 다음과 같습니다. (오류 번역이 있을 수 있습니다.)

타임리프에서 코드 재사용을 개선하기 위해 재사용이 가능한 레이아웃과 템플릿을 작성할 수 있도록 도와주는 라이브러리입니다.

이 라이브러리는 Spring Boot 1.5.8.RELEASEspring-boot-starter-thymeleaf 스타터 의존성에 포함되어 있습니다.

만약 Spring Boot starter를 사용하지 않거나, 다른 환경에서 사용하실 경우 공식 문서의 설치 부분을 참고하시기 바랍니다.


thymeleaf-layout-dialect의 간단한 사용 예제

공식 Github에 있는 예제를 기준으로 설명드리려 합니다.


1. 공통으로 사용할 Layout html 작성하기

먼저 컨텐츠 페이지에서 공통적으로 사용할 html을 작성합니다.
이 공통적으로 사용될 layout 파일명을 comm_layout.html이라 하겠습니다.

<!DOCTYPE html>
<html 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>
      <p>My footer</p>
      <p layout:fragment="custom-footer">Custom footer here</p>
    </footer>
  </body>
</html>

2. 실제 컨텐츠 페이지

컨텐츠 페이지는 다음과 같습니다.

<html
  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
  layout:decorator="comm_layout"
>
  <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>
    <footer>
      <p layout:fragment="custom-footer">
        This is some footer content from the content page
      </p>
    </footer>
  </body>
</html>

컨텐츠 페이지에서 html의 태그 안에서 layout:decorator 속성이 있습니다.
해당 속성은 공통 레이아웃을 지정하는 속성으로 위 1번에서 사용한 레이아웃 파일명을 작성해줍니다.
확장자는 제거한 파일명을 적어주며, 실제 Spring Boot에서 사용하는 경로에 맞춰서 작성하게 됩니다.

위 공통 레이아웃과 실제 컨텐츠를 적용한 페이지는 다음과 같은 결과물로 만들어지게 됩니다.

<!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>
    <footer>
      <p>My footer</p>
      <p>This is some footer content from the content page</p>
    </footer>
  </body>
</html>

위의 결과물을 보면 동작 원리나 방식에 대한 이해가 더 잘 될것입니다.
공통 레이아웃에 실제 컨텐츠 페이지를 덮어둔 형식으로 결과가 나오게 됩니다.
하지만 공통 레이아웃의 layout:fragment= 부분은 실제 컨텐츠 페이지의 선언된 내용으로 치환하게 됩니다.

thymeleaf-layout-dialect의 layout namespace를 사용하여 기본적인 방법을 알아봤습니다.

Thymeleaf에서 실제로 dialect를 사용하는 예제는 Thymeleaf에서 템플릿 형식으로 사용하기 포스팅을 참고해 주세요.


Written by@MHLab
로또는 흑우집합소 🎲
와인관리, 시음노트, 셀러관리는 마와셀 🥂

🫥 My Service|  📜 Contact|  💻 GitHub