타임리프 레이아웃 다이얼렉트를 이용하여 레이아웃을 재사용할 수 있다.
의존관계 정의
#maven
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
#gradle
dependencies {
implementation('nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect')
}
공통 레이아웃이 되는 템플릿을 '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>
대체하고 싶은 요소에 layout:fragment 속성을 부여한다.
[컨트롤러 메서드]
@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>
[응답 화면]