9.레이아웃 재사용

리얼브로·2023년 2월 24일

thymeleaf

목록 보기
9/10

타임리프 레이아웃 다이얼렉트를 이용하여 레이아웃을 재사용할 수 있다.

9-1. 환경설정

  • 의존관계 정의

    #maven
    <dependency>
      <groupId>nz.net.ultraq.thymeleaf</groupId>
      <artifactId>thymeleaf-layout-dialect</artifactId>
    </dependency>  
    
    #gradle
    dependencies {
    	implementation('nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect')
    }

9-2. 공통 레이아웃 템플릿 정의

  • 공통 레이아웃이 되는 템플릿을 'Decorator' 라고 한다.

  • main_template.html

    <html xmlns:th="http://www.thymeleaf.org"
    	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
    
    <head>
    	<title>Main</title>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    	<script src="/js/jQuery-2.1.4.min.js"></script>
    </head>
    
    <body>
    
    	<div>
    		<p>페이지 헤더</p>
    	</div>
    	
    	<div layout:fragment="content">
    		
    	</div>
    	
    	<div>
    		<p>© 2019 ALL RIGHT RESERVED</p>
    	</div>
    
    </body>
    </html>
    

9-2. 레이아웃 적용 템플릿

  • 대체하고 싶은 요소에 layout:fragment 속성을 부여한다.

  • [요청] http://localhost:8080/ch0809/home0101

  • [컨트롤러 메서드]

    @GetMapping("ch0809/home0101")
    public String home0101(Model model) {
      model.addAttribute("msg", "Hello world!");
    
      return "ch0809/home0101";
    }
  • [뷰 파일]

    <html xmlns:th="http://www.thymeleaf.org"
    	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
    	layout:decorate="~{ch0809/layouts/main_template}">
    <head>
    	<title>Home</title>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    	<link rel="stylesheet" href="../../static/css/style.css" th:href="@{/css/style.css}"/>
    </head>
    <body>
    <div layout:fragment="content">
    	<p>Home0101 Content</p>
    </div>
    </body>
    </html>
  • [응답 화면]

0개의 댓글