본문 바로가기
Etc/Thymeleaf

Thymeleaf - 템플릿 레이아웃(2)

by HwaHyun 2023. 7. 25.

Thymeleaf - 템플릿 레이아웃 에서 이어지는 내용 입니다.

 

이전 포스팅에서 다룬 개념을 <head> 뿐만 아니라 <html> 전체에 적용할 수도 있다.

 

TeamplateController

@GetMapping("layoutExtend")
public String layoutExtends(){
    return "template/layoutExtend/layoutExtendMain";
}

 

template/layoutExtend/layoutFile.html

<!DOCTYPE html>
<html th:fragment="layout (title, content)" xmlns:th="http://www.thymeleaf.org">
<head>
  <title th:replace="${title}">레이아웃 타이틀</title>
</head>
<body>
<h1>레이아웃 H1</h1>
<div th:replace="${content}">
  <p>레이아웃 컨텐츠</p>
</div>
<footer>
  레이아웃 푸터
</footer>
</body>
</html>

 

template/layoutExtend/layoutExtendMain.html

<!DOCTYPE html>
<html th:replace="~{template/layoutExtend/layoutFile :: layout(~{::title}, ~{::section})}"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <title>메인 페이지 타이틀</title>
</head>
<body>
<section>
    <p>메인 페이지 컨텐츠</p>
    <div>메인 페이지 포함 내용</div>
</section>
</body>
</html>

 

 

코드 실행 결과

 

정리

  • layoutFile.html 을 보면 기본 레이아웃을 가지고 있는데, <html> 에 th:fragment 속성이 정의되어 있다.
  • 이 레이아웃 파일을 기본으로 하고 여기에 필요한 내용을 전달해서 부분부분 변경하는 것으로 이해하면 된다.
  • layoutExtendMain.html 는 현재 페이지인데, <html> 자체를 th:replace 를 사용해서 변경하는 것을 확인할 수 있다. 
  • 결론적으로 layoutFile.html 에 필요한 내용을 전달하면서 <html> 자체를 layoutFile.html 로 변경한다.

'Etc > Thymeleaf' 카테고리의 다른 글

Thymeleaf - 템플릿 레이아웃  (0) 2023.07.25
Thymeleaf - 템플릿 조각  (0) 2023.07.25
Thymeleaf - 자바스크립트 인라인  (0) 2023.07.25
Thymeleaf - 블록  (0) 2023.07.25
Thymeleaf - 주석  (0) 2023.07.25