Fragment
✒️ 2025-06-25 17:39 내용 수정
참고 자료 : Thymeleaf Template Layout, Ben Weidig's Templating with Thymeleaf: Fragments and Resuability
Fragment
- 웹 템플릿에서 재사용 가능한 HTML 구성 요소를 정의하고 관리하는 기능이다.
- 자주 사용하는 템플릿을 정의하여 웹 페이지의 구조와 디자인 요소를 모듈화할 수 있다.
- 모듈화한 템플릿을 재사용할 수 있고 유지 보수하기가 편리하다.
Fragment 사용
src/main/resources/templates디렉터리 하위에fragments디렉터리를 새로 만든 후, fragment로 사용할 HTML 파일을 생성한다.- fragment화할 요소를
th:fragment로 지정한다.
<!-- templates/fragments/header.html -->
<div th:fragment="top-header">
<h2>Header</h2>
</div>
- fragment를 사용할 HTML 파일에서
th:insert나th:replace를 사용하여~{}표현식으로 fragment를 가져온다.th:insert는 요소 내에 추가하고,th:replace는 요소를 대체한다.
<!-- index.html -->
<div th:insert="~{fragments/header :: top-header}"></div>
<div th:replace="~{fragments/header :: top-header}"></div>
<!-- 파일 내용 전체를 가져옴 -->
<div th:replace="~{fragments/header}"></div>