basic/Java
Thymeleaf 공통레이아웃 만들기
ekgoddldi
2022. 5. 6. 18:17
공통으로 사용할 레이아웃을 layout/common.html이라는 이름으로 만들고
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<th:block th:fragment="setContent(content)">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Common Template</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js" defer></script>
<!-- Popper JS -->
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" defer></script>
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" defer></script>
</head>
<body>
<th:block th:replace="${content}"></th:block>
</body>
</th:block>
</html>
그 템플릿을 사용할 페이지에서 이렇게 넣어준다
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<th:block th:replace="~{/layout/common :: setContent(~{this::content} )}">
<th:block th:fragment="content">
<h1>Index Page</h1>
</th:block>
</th:block>
Thymeleaf의 fragment로 만든 content 영역에 내용에 들어가게 연결해 준다.