템플릿 레이아웃 확장

앞서 이야기한 개념을 <head> 정도에만 적용하는게 아니라 <html> 전체에 적용할 수도 있습니다.

TemplateController

package hello.thymeleaf.basic;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/template")
public class TemplateController {

		...

    @GetMapping("/layoutExtend")
    public String layoutExtend() {
        return "template/layoutExtend/layoutExtendMain";
    }
}
<!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>

이 파일이 껍데기입니다.

예를 들어, 사이트가 100페이지 되는데 다 모양이 똑같다고 합시다. 여기서 바뀌어야할 부분은 div 태그 부분과 타이틀의 제목입니다.

<!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>

layoutExtendMain.html 는 현재 페이지인데, <html> 자체를 th:replace 를 사용해서 변경합니다. 그러니까 <html>로 감싼 전체가 통으로 교체가 되는 것입니다.

그런데 그냥 교체하지는 않고 title과 section을 넘깁니다.

layoutFile.html 을 보면 기본 레이아웃을 가지고 있는데, <html> 에 th:fragment 속성이 정의되어 있습니다.

th:fragment="layout (title, content)" 에 있는 titlecontent에 layoutExtendMain.html 에서 넘긴 title과 section이 담기고 해당 영역이 바뀌게 됩니다.