▼ Backend/스프링 (Spring)

Spring Boot | Thymeleaf Layout 공통 Header, Footer 설정하기

Valar 2021. 7. 22. 12:23
반응형

▶ Thymeleaf Layout

Header, Footer와 같이 공통적으로 사용되는 코드를 화면마다 작성하지 않고 레이아웃 처리를

통해 공통 내용은 고정적으로 설정됨으로써, 본래의 콘텐츠 내용에 집중할 수 있게 도와준다.

 

1. thymeleaf-layout-dialect 의존성 주입

Maven

 

<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    <version>2.5.0</version>
</dependency>

 

 

Gradle

 

implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'

 

 

2. 공통 화면 작성 Head, Header, Footer

우선 공통으로 사용될 화면들을 목적에 맞게 각 HTML에 작성한다.

fragment의 이름을 정한다. <th:block th:fragment="이름"></th:block> 

파일 경로 : /templates/fragments/head.html

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <th:block th:fragment="headFragment">
      <head>
          <meta charset="UTF-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
          <title>Melon</title>
      </head>
  </th:block>
</html>

 

 

파일 경로 : /templates/fragments/header.html

다른 fragment 설정과는 다르게 param1이라는 매개변수를 가지고 있는데
thymeleaf layout를 통해 데이터 전달이 가능하다는 것을 보여주기 위해 추가했다.

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <th:block th:fragment="headerFragment(param1)">
      <div>
          <h2 th:text="${param1}"></h2>
      </div>
  </th:block>
</html>

 

 

/templates/fragments/footer.html

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <th:block th:fragment="footerFragment">
      <div>
          <h2>Footer</h2>
      </div>
  </th:block>
</html>

 

 

3. Layout 설정

fragment로 작성된 파일들의 레이아웃을 설정한다.

해당 영역을 fragment로 치환

<th:block th:replace="파일 경로 :: Fragment명"></th:block>

해당 layout을 사용하는 내용 출력

<th:block layout:fragment="이름"></th:block>

파일 경로 : /templates/layout/default_layout.html

layout 속성 사용
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"

해당 부분이 headerFragment(header.html)의 param1 데이터로 전달된다.
headerFragment('Header')

Tag 자체를 데이터로 전달할 수도 있다.
<title>Hello</title>
headerFragment(~{::title})

 

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
  <th:block th:replace="fragments/head :: headFragment"></th:block>
  <body>
      <div>
          <th:block th:replace="fragments/header :: headerFragment('Header')"></th:block>
          <th:block layout:fragment="content"></th:block>
          <th:block th:replace="fragments/footer :: footerFragment"></th:block>
      </div>
  </body>
</html>

 

 

 

4. layout fragment 설정

파일 경로 : /templates/dashboard.html

layout:decorator="위에서 만든 레이아웃_경로 설정"

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="layout/default_layout">
  <!-- Page Content -->
  <th:block layout:fragment="content">
      <div>Dashboard</div>
  </th:block>
</html>

 

 

dashboard.html 결과

 

 


Reference

반응형