[Thymeleaf] 타임리프 header, footer 레이아웃 적용하기 (간단 버전)

레이아웃이란?

etc-image-0

레아아웃을 사용하는 이유는 만약 100개의 페이지에 똑같은 header와 footer가 들어갈 경우

각각의 HTML마다 똑같은 header와 footer를 추가하는 것은 상당히 비효율적이고 유지보수면에서도 좋지 않다.

그래서 반복되는 화면이 있어 HTML 코드를 줄일 때 레이아웃을 적용하면 상당히 효과적이다.

 


타임리프 레이아웃 적용하기

의존성추가

레이아웃 기능을 사용하기 위해 아래의 의존성을 build.gradle에 추가하자.

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

 

폴더 구조

etc-image-1

 

 

/layout/fragments/header.html

각 페이지마다 상단 부분에 반복적으로 들어가는 내용을 추가한다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<th:block th:fragment="headerLayout">
  <head>
    <title>Board List</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <script src="/js/jquery-3.6.0.min.js"></script>
    <script src="/js/bootstrap.min.js"></script>
  </head>

  <h1>
    헤더입니다.
  </h1>
  
</th:block>
</html>

 

 

 

/layout/fragments/footer.html

각 페이지마다 하단 부분에 반복적으로 들어가는 내용을 추가한다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<th:block th:fragment="footerLayout">
  <footer>
    <div class="mt-5">
      <div class="text-center">
        <p>
          푸터입니다.
        </p>
      </div>
    </div>
  </footer>
</th:block>
</html>

 

/layout/layout.html

분리한 header와 footer를 지정해준다.

<body> 태그 안에 들어가는 레이아웃은 페이지의 본문 내용이 된다.

( xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" 은 해당 파일을 기본 레이아웃으로 적용한다는 것)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<th:block th:replace="/layout/fragments/header :: headerLayout"></th:block>

<body>
<th:block layout:fragment="content"></th:block>
</body>

<th:block th:replace="/layout/fragments/footer :: footerLayout"></th:block>
</html>

이제 레이아웃을 적용할 준비가 끝났다.

만들어 놓은 레이아웃에 본문 내용을 적용해보자.

 

 

레이아웃에 본문 내용 적용 - index.html

( layout:decorator="~{layout/layout}" 은 기본 레이아웃을  layout/layout.html 파일을 사용한다는 뜻 )

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/layout}">
<th:block layout:fragment="content">
    <p>
        본문내용입니다.
    </p>
</th:block>
</html>

<th:block layout:fragment="content"> 안에 작성한 코드가 layout.html에서 content라는 부분에 들어가

아래 처럼 레이아웃이 적용된 것을 볼 수 있다.

etc-image-2

반응형