이전에 사용했던 템플릿 조각을 적극적으로 활용한 것이 템플릿 레이아웃이라고 할 수 있다. 이전 것을 이해했다면 템플릿 레이아웃도 쉽게 이해할 수 있다.
템플릿 레이아웃의 경우, 모든 페이지에 공통으로 활용해야 할 부분이 있고 일부 페이지에서만 특별하게 추가해야하는 경우가 있을 때 이를 처리하는 것을 도와준다.
아래 예제는 <head> 태그에 css, js 등의 정보를 담아두고 각 페이지마다 필요한 부분이 있으면 추가하여 사용할 수 있도록 한다.
아래와 같이 base.html 에 작성한다. 아래를 이해하는 것은 템플릿 조각과 동일하게 이해하면 된다.
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="common_header(title,links)">
<title th:replace="${title}">레이아웃 타이틀(head)</title>
<!-- 공통 -->
<link rel="stylesheet" type="text/css" media="all" th:href="@{/css/awesomeapp.css}">
<link rel="shortcut icon" th:href="@{/images/favicon.ico}">
<script type="text/javascript" th:src="@{/sh/scripts/codebase.js}"></script>
<!-- 추가 -->
<th:block th:replace="${links}"/>
</head>
<head th:fragment="common_header(title,links)">
에서 코드조각의 이름(common_header)을 지정해주고, 파라미터로 넘어오는 값에 변수명의 개념으로 이름을 붙여준다. 이 변수명을 통해 대체 될 곳에 넣어주게 된다. 이 부분은 이전 글인 템플릿 조각에서 설명하지 않은 부분이므로 뒤에서 함께 추가로 설명하겠다.<title th:replace="${title}">레이아웃 타이틀(head)</title>
부분에 th:replace
가 들어가있다.<th:block th:replace="${links}"/>
부분에서 다시 한 번 th:replace
가 들어가있다.th:replace
가 있다는 점 !레이아웃을 활용할 메인 페이지는 아래와 같다. 템플릿 조각에서 이해한 부분을 바탕으로 이해하면 된다.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="template/layout/base :: common_header(~{::title},~{::link})">
<title>메인 타이틀</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">
</head>
<body>
메인 컨텐츠
</body>
</html>
<head th:replace="template/layout/base :: common_header(~{::title},~{::link})">
<head> 태그를 replace 하기 위해 경로와 이름을 통해 불러온다. 그리고 두 가지의 파라미터를 넘겨주는 새로운 문법이 등장한다.~{::title}
, ~{::link}
를 이용해 아래 <title>, <link> 태그들을 넘겨주게 된다. 그러면 ~{::title}
부분에 <title>메인 타이틀</title>
태그가 들어가고, ~{::link}
에는 <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
, <link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">
이 두 개의 태그가 넘겨지게 된다.<head th:fragment="common_header(title,links)">
태그에 따라 첫 번째로 넘어오는 값은 title이라는 변수명으로, 두 번째로 넘어오는 값은 links라는 변수명에 저장된다고 생각한다.<title th:replace="${title}">레이아웃 타이틀(head)</title>
부분에서 변수명 title이 사용되어 "${title}"
에 태그가 대입되어 넘겨진 태그로 치환된다.<th:block th:replace="${links}"/>
또한 위와 동일하게 전달해준 두 개의 태그가 들어가게 된다.결과적으로 중간에는 공통으로 넣은 태그들은 동일하게 들어가게 되고, 파라미터로 넘겨준 태그들을 통해 태그가 바뀌어(replace), 아래와 같이 페이지가 출력되게 된다.