백엔드/spring

spring boot - thymeleaf layout dialect 적용

DuckCow 2023. 2. 16. 13:14

 

 

https://wildeveloperetrain.tistory.com/136

 

Spring Boot 타임리프 Thymeleaf layout 적용하는 방법

타임리프(Thymeleaf)에 대해서 간단하게, 타임리프는 서버 사이드 템플릿 엔진(Template Engine)의 한 종류로, 쉽게 컨트롤러가 전달하는 데이터를 이용하여 동적으로 화면을 구성할 수 있게 해주는 역

wildeveloperetrain.tistory.com

https://blog.outsider.ne.kr/1004

 

Thymeleaf에서 레이아웃 기능을 지원하는 Thymeleaf Layout Dialect :: Outsider's Dev Story

전에 [Thymeleaf에 대한 얘기를 올렸었지만](http://blog.outsider.ne.kr/969) 어쨌든 아직 쓰고 있기는 하다. 뷰페이지를 작업하면 어떤 어플리케이션을 만들던지 간에 당연히 헤더나 메뉴같은 공통적인 부

blog.outsider.ne.kr

 

를 참고하여 

spring boot thymeleaf layout를 적용해 보았다.

1.왜 dialect를 사용하는가?

기존 thymeleaf 의 경우, fragments 로 단위를 나눠서 각 페이지들의 html 파일(ex. home.html) 에서 fragments 를 include 하는 방식이다.

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  <body>
    <div th:fragment="copy">
      &copy; 2011 The Good Thymes Virtual Grocery
    </div>
  </body>
</html>

각 페이지를 만들때마다 header,footer와 같은 fragments 조각들을 찾아 끼워넣는 방식이다.

dialect의 경우, 이런 조각들을 조립해놓은 fragments layout을 만들어 layout을 각 페이지 파일에 끼워넣는 방식으로 전체 페이지의 layout를 바꿔야할때 더 관리하기 편하다는 장점이 있다.

구현

나는 gradle을 사용하기 때문에 https://mvnrepository.com/

에서 내 버전에 맞는 dependency를 추가했다.

// https://mvnrepository.com/artifact/nz.net.ultraq.thymeleaf/thymeleaf-layout-dialect
implementation group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '3.0.0'

 

https://wildeveloperetrain.tistory.com/136 를 참고하여 따라한 결과,

 

Spring Boot 타임리프 Thymeleaf layout 적용하는 방법

타임리프(Thymeleaf)에 대해서 간단하게, 타임리프는 서버 사이드 템플릿 엔진(Template Engine)의 한 종류로, 쉽게 컨트롤러가 전달하는 데이터를 이용하여 동적으로 화면을 구성할 수 있게 해주는 역

wildeveloperetrain.tistory.com

나는 여기서 layout에 navigation bar를 추가하고 싶었다.

https://www.w3schools.com/bootstrap/bootstrap_navbar.asp

를 참고하여 

<!DOCTYPE html>
<html lagn="ko"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <meta charset="UTF-8" />
    <title>thymeleaf layout</title>
    <meta name="viewport" content="width=device-width, maximum-scale=1.0, minimum-scale=1, user-scalable=yes,initial-scale=1.0" />
    <!-- content script -->
    <th:block layout:fragment="css"></th:block>
    <!-- content script -->
    <th:block layout:fragment="script"></th:block>
</head>
<body>
<!-- header fragment 사용 -->
<th:block th:replace="fragments/header :: headerFragment"></th:block>
<!-- navigation_bar fragment 사용 -->
<th:block th:replace="fragments/navigation_bar :: navigation_barFragment"></th:block>
<!-- content fragment 사용 -->
<th:block layout:fragment="content"></th:block>
<!-- footer fragment 사용 -->
<th:block th:replace="fragments/footer :: footerFragment"></th:block>
</body>
</html>

navigation bar 임시 구현. bootstrap 을 적용하지 않아  이상하지만, 일단 bootstrap은 기능 구현을 마친 후 다시 돌아오자.