템플릿 조각

학습 페이지

웹개발 하다보면 페이지에 일정한 패턴이 많다. 이를 다 그때그때 만드는게 아니라 조각조각내고 템플릿으로 만들어서 필요한 페이지에서 불러다 쓸 수 있다.

먼저 footer라고 불리는 template fragment를 보자.

<!DOCTYPE html>
<html xmlns:th="<http://www.thymeleaf.org>">
<body>
<footer th:fragment="copy"> //이 조각의 이름을 copy로 설정함.
 푸터 자리 입니다.
</footer>
<footer th:fragment="copyParam (param1, param2)">
 <p>파라미터 자리 입니다.</p>
 <p th:text="${param1}"></p>
 <p th:text="${param2}"></p>
</footer>
</body>
</html>

앞으로 만들 페이지에서 footer는 모두 이 html이 담당할 것임.

fragmentMain페이지에서 해당 footer를 가져다가 써보자.

<!DOCTYPE html>
<html xmlns:th="<http://www.thymeleaf.org>">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<h1>부분 포함</h1>
<h2>부분 포함 insert</h2>
<div th:insert="~{template/fragment/footer :: copy}"></div>
<h2>부분 포함 replace</h2>
<div th:replace="~{template/fragment/footer :: copy}"></div>
<h2>부분 포함 단순 표현식</h2>
<div th:replace="template/fragment/footer :: copy"></div>
<h1>파라미터 사용</h1>
<div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터2')}"></div>
</body>
</html>

Main에서 footer를 가져다가 쓰는 부분은 이 부분이다.

<!--insert-->
<div th:insert="`{template/fragment/footer :: copy}"></div>
<!--replace-->
<div th:replace="~{template/fragment/footer :: copy}"></div>

타임리프에서 fragment를 가져다가 쓰는 문법은 위와 같다.

여기서 th:insertth:replace라는 다른 속성이 보인다. 차이는 눈으로 보

자.

Untitled

대체 무슨 차이일까?

소스를 보자.

Untitled

보면 insert는 <div> 안에 푸터를 넣었고, replace는 아예 <div>를 본인으로 대체해버렸다. 그래서 <div>가 없어졌다.