여러 템플릿을 작성할 때 공통적인 내용을 별도 파일로 추출하여
효율적으로 사용할 수 있게 해주는 기능이다.
[헤더 프레그먼트]
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="header">
<p>페이지 헤더</p>
</div>
</body>
</html>
[푸터 프래그먼트]
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="footer">
<p>© 2019 ALL RIGHT RESERVED</p>
</div>
</body>
</html>
정의한 프래그먼트를 참조해서 템플릿에 불러온다.
<html>
<head>
<title>Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>
<p>페이지 헤더</p>
</div>
<div>
<h1>Hello world!</h1>
</div>
<div>
<p>© 2019 ALL RIGHT RESERVED</p>
</div>
</body>
</html>
th:insert 속성을 이용하여 프래그먼트를 삽입한다.
[컨트롤러 메서드]
@GetMapping("ch0808/home0101")
public String home0101(Model model) {
model.addAttribute("msg", "Hello world!");
return "ch0808/home0101";
}
[뷰 파일]
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div th:insert="~{ch0808/fragments/header::header}"></div>
<div>
<h1 th:text="${msg}">greeting</h1>
</div>
<div th:insert="~{ch0808/fragments/footer::footer}"></div>
</body>
</html>
[응답 화면]
th:replace 속성을 이용하여 프래그먼트를 대체한다.
insert 추가와 replace 교환은 타임리프 가 파싱 되고 나서 순수 html 코드 소스 보기 하면
처리된 내용이 다르다. (insert 일 경우 html 요소가 추가되는 차이)
[컨트롤러 메서드]
@GetMapping("ch0808/home0201")
public String home0201(Model model) {
model.addAttribute("msg", "Hello world!");
return "ch0808/home0201";
}
[뷰 파일]
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div th:replace="~{ch0808/fragments/header::header}"></div>
<div>
<h1 th:text="${msg}">greeting</h1>
</div>
<div th:replace="~{ch0808/fragments/footer::footer}"></div>
</body>
</html>
[응답 화면]