Fragment

✒️ 2025-06-25 17:39 내용 수정


참고 자료 : Thymeleaf Template Layout, Ben Weidig's Templating with Thymeleaf: Fragments and Resuability


Fragment

Fragment 사용

  1. src/main/resources/templates 디렉터리 하위에 fragments 디렉터리를 새로 만든 후, fragment로 사용할 HTML 파일을 생성한다.
  2. fragment화할 요소를 th:fragment로 지정한다.
<!-- templates/fragments/header.html -->
<div th:fragment="top-header">
	<h2>Header</h2>
</div>
  1. fragment를 사용할 HTML 파일에서 th:insertth: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>