Spring
스프링MVC2편 타임리프 - 기본기능 : 템플릿 조각
sami355
2022. 8. 10. 13:20
인프런 김영한님의 스프링 mvc2편을 보고 정리한 글입니다.
무엇을 배웠나요?
- th:fragment 가 있은 태그는 다른 곳에 포함되는 코드 조각으로 이해하면 된다.
- template/fragment/footer :: copy, template/fragment/footer.html 템플릿에 있는 th:fragment=”copy” 라는 부분을 템플릿 조각으로 가져와서 사용한다는 의미이다.
- 부분 포함 insert th:insert를 사용하면 현재 태그 내부에 추가 된다.
- 부분 포함 replace th:replace 를 사용하면 현재 태그(div)를 대체한다.
- 부분 포함 단순 표현식~{…} 을 사용하는 것이 원칙이지만 코드가 단순하면 이 부분을 생략할 수 있다.
- 파라미터를 전달하여 동적으로 조각을 렌더링 할 수도 있다.
코드
<html xmlns:th="http://www.thymeleaf.org">
<body>
<footer th:fragment="copy">
푸터 자리 입니다.
</footer>
<footer th:fragment="copyParam (param1, param2)">
<p>파라미터 자리 입니다.</p>
<p th:text="${param1}"></p>
<p th:text="${param2}"></p>
</footer>
</body>
</html>
<!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>