본문 바로가기
Dev/Java

[Spring Boot] Thymeleaf 뷰 레이아웃 설정 및 사용하는 방법

by 데브길길잇 2024. 7. 26.
728x90
반응형

 

 

안녕하세요 dev-길길IT입니다.

 

Thymeleaf는  spring boot에서 view template(뷰 템플릿)으로 사용됩니다. 이러한 view template들의 특징은 spring mvc 구조에서 controller가 전달하는 데이터를 활용하여 화면을 동적으로 구성하도록 합니다. 기존에 많이 사용하던 jsp와 다르게 설정도 간단하고 더 기능도 많은데요. 

 

오늘은 이 Thymeleaf를 이용해서 view layout을 설정하고 사용하는 방법을 알아보겠습니다.

 

 

[Spring Boot] Thymeleaf 뷰 레이아웃 설정 및 사용하는 방법

 

※ 목차

1. dependency, properties 셋팅
2. thymeleaf 디렉토리 구조
3. sprinig boot thymeleaf 레이아웃 적용 결과

     

    1. dependency, properties 셋팅

     

     

    Spring boot에 Thymeleaf를 적용해주기 위해서 먼저 dependency를 추가해주어야 합니다. 2가지를 추가해줄텐데요. 여기서 thymeleaf-layout-dialect는 레이아웃과 재사용이 가능한 템플릿을 구축할 수 있는 오픈소스 라이브러리입니다.

     

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

     

     

    # application.properties
    
    spring.application.name=springBootProject
    
    # 재부팅 없이 정적 뷰 파일 바로 반영
    spring.devtools.livereload.enabled=true
    
    # thymeleaf view 위치
    spring.thymeleaf.prefix=classpath:/templates/
    spring.thymeleaf.suffix=.html
    
    # thymeleaf 캐시를 남기지 않음 -> 즉각 반영
    spring.thymeleaf.cache=false
    
    # 디렉토리에 파일이 없으면 에러 발생
    spring.thymeleaf.check-template-location=true

     

    그 다음 application.properties에 추가적인 설정들을 해줍니다. 여기에서는 thymeleaf의 view 엔진 설정을 위해서 경로와 html suffix 등의 설정들을 해주게 됩니다. 또한 개발할 때 디버깅이 편하도록 로컬에 캐시를 남기지 않는 설정 등을 추가적으로 해주면 됩니다. 그 외에 필요한 설정들이 있다면 추가적으로 하셔도 됩니다.


     

     

    2. thymeleaf 디렉토리 구조

     

    spring boot에서의 thymeleaf 디렉토리 구조는 다음과 같습니다. 기본적인 layout을 작성하는 폴더가 있고, fragment 즉, 조각들을 별도로 관리하는 폴더가 있습니다. 마지막으로 실제 페이지를 구성하는 pages 폴더가 있는데요. 이것들은 자동으로 생성되는 것은 아니고 별도로 만들어주어야 합니다. 사용성을 위해서 분리해놓은 것입니다. 기본적으로 application.properties에서 설정했던 templates 폴더 아래쪽에 다 위치해주면 됩니다.

     

    # defaultLayout.html
    
    <!DOCTYPE html>
    <!--라이브러리 참조 : Thymeleaf & Thymeleaf Layout -->
    <html lang="en"
          xmlns:th="http://www.thymeleaf.org"
          xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
    
    <body>
    <!--Header 영역 참조-->
    <header th:replace="fragments/header :: HeaderFragment"></header>
    
    <!--Content 영역 참조-->
    <th:block layout:fragment="Content"></th:block>
    
    <!--Footer 영역 참조-->
    <footer th:replace="fragments/footer :: FooterFragment"></footer>
    </body>
    </html>

     

    먼저 defaultLayout의 경우 각각 조각화된 framgment들을 하나로 합쳐주기 위한 파일입니다.

     

    # header.html
    
    <!DOCTYPE html>
    <html lang="en"
          xmlns:th="http://www.thymeleaf.org"
          th:fragment="HeaderFragment">
    <div style="border: solid 1px yellow; background-color: Gray;">
        <h1>Header 영역입니다.</h1>
    </div>
    </html>

     

    headerFragment에는 헤더 영역을 작성해줍니다. 여기서 xmlns:th="http://www.thymeleaf.org"는 해당 페이지가 thymeleaf template이라고 선언을 해주는 의미이구요. th:fragment는 thymeleaf의 fragment를 지정해주는 것을 의미합니다.

     

    # content.html
    
    <!DOCTYPE html>
    <html lang="en"
          xmlns:th="http://www.thymeleaf.org"
          th:fragment="FooterFragment">
    <div style="border: solid 1px blue; background-color: yellow;">
        <h1>Footer 영역입니다.</h1>
    </div>
    </html>

     

    footerFragment에는 풋터 영역을 작성해줍니다.

     

    # config.html
    
    <!DOCTYPE html>
    
    <html lang="en"
          xmlns:th="http://www.thymeleaf.org"
          th:fragment="ConfigFragment">a
    <head>
    </head>
    </html>

     

    configFragment에는 공통적으로 사용할 js나 css 등을 선언해주게 되는데, 저는 skip하겠습니다.

     

    # index.html
    
    <!DOCTYPE html>
    <!-- Default Layout Import-->
    <html lang="en"
          xmlns:th="http://www.thymeleaf.org"
          xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
          layout:decorate="~{layout/defaultLayout}"
          layout:fragment="Content"
    >
    <head>
        <title>테스트 페이지 </title>
    
        <style th:inline="css" type="text/css">
            body {
                margin: 30px;
                border: 1px solid red;
            }
        </style>
    
    </head>
    
    <body>
    <div>
        <h1 style="height:500px;">Content 영역입니다.</h1>
    </div>
    </body>
    </html>

     

    그리고 실제 페이지를 구성하는 index.html 페이지 입니다. 여기서 latout:decorate는 해당 경로에 있는 레이아웃을 불러올 때 사용합니다. 그래서 index.html에서 thymeleaf로 구성된 fragment들을 불러올 수 있게 됩니다.

     


     

    3. sprinig boot thymeleaf 레이아웃 적용 결과

     

     

    spring boot에 위와 같이 thymeleaf 레이아웃을 적용한 결과입니다. header와 content, footer가 의도한 대로 잘 나눠졌네요. 이렇게 관리하기가 용이하고, 만들어진 레이아웃은 다른 페이지에서도 쉽게 재활용 할 수 있습니다.

     

     


     

     

     

     

    마무리

     

    오늘은 Spring Boot Thymeleaf 뷰 레이아웃 설정 및 사용하는 방법을 알아보았습니다. 많은 뷰 템플릿이 있지만 기존 jsp의 단점들을 보완해서 더 빠르고 가벼우면서도 강력하게 개발을 도와주는 thymeleaf를 써보시면 어떨까요? 여러분의 개발 생산성을 더욱 높여줄 것입니다.

     

    도움이 되시기를 바라며, 오늘도 읽어주셔서 감사합니다.

     

     

    728x90
    반응형

    댓글