dialects-layout 사용하기, 스프링부트 layout 사용법

Jay_u·2023년 7월 9일
0

타임리프 정리

목록 보기
2/2

Layout이란?

JSP에는 tiles 기능을 활용해 반복되는 구조 Header, Footer, Nav 등을 틀을 정해놓고 Contents만 갈아끼우는 식으로 구성할 수 있다.

타임리프에서도 비슷한 기능을 지원해준다. 바로 layout이다.
먼저 타임리프의 공식 사이트에서 업데이트, 튜토리얼 등을 볼 수 있다.
https://github.com/ultraq/thymeleaf-layout-dialect


적용방법

1. gradle 설정

build.gradle 파일로 가서 다음과 같이 적어준다.

    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'

2. dependency 추가

본 프로젝트에는 application.yml, yml 파일을 쓰고 있는데 dependency에 다음과 같이 추가해준다. 추가하고 빌드 되는 시간 기다리자!

  spring:
    thymeleaf:
      enabled: true
      dialects: nz.net.ultraq.thymeleaf.LayoutDialect
      prefix: classpath:/templates/
      suffix: .html
      cache: false
      mode: HTML
      encoding: UTF-8
      servlet:
        content-type: text/html;charset=UTF-8
      view-names: error
      check-template-location: true
      template-resolver-order: 0

이제 templates 폴더 아래에 있는 .html 로 끝나는 파일을 파일명만 입력하면 찾을 수 있게 되었다.

3. 구조짜기

본 프로젝트에서는 layout을 활용해 다음과 같이 구조를 짰다.
fragments에서는 중복적인 부분 예컨데 header나 footer 파일을 넣는다.
css나 js 혹은 라이브러리를 정리한 config 파일을 만들 수도 있다.

layout에서는 fragments 파일과 우리가 계속해서 수정해서 보여줄 Contents 파일을 조립하는 곳이다.

restaurant은 내가 사용할 Contents 파일이다.

4. default_layout.html 작성

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      lang="en">  // 추가 안하면 못씀

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="/css/main.css">
    // 이 부분에 라이브러리나 css, js 사용할 것들 정리할 수 있음
</head>

<body>
<th:block th:replace="fragments/header :: header"></th:block> // 헤더 부분을 replace 하겠다는 의미이다. footer도 같은 방식으로 작성하면 된다.

<section layout:fragment="content"></section>
// content 부분을 section 태그를 활용해서 집어넣겠다는 의미이다. th:block, div 아무거나 해도 상관없다. 단 태그를 사용할 거라면 content html에서 내용 넣을 부분의 태그를 동일하게 잡아줘야 한다.
</body>

</html>

5. content.html 작성

<html xmlns:th="http://www.thymeleaf.org" lang="en"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{/layout/default_layout}">
      // decorate를 활용해 현재 파일명으로 어떤 레이아웃을 쓸건지 설정해준다.
<body>
    <section class="contents" layout:fragment="content">
    // 이 부분의 내용이 레이아웃의 content 부분에 반영된다.
	</section>
</body>
</html>
profile
정확한 정보를 전달할려고 노력합니다.

0개의 댓글