[Thymeleaf] 템플릿 레이아웃 개념

Kade Jeon·2024년 2월 23일
0

Thymeleaf

목록 보기
17/22

템플릿 레이아웃

이전에 사용했던 템플릿 조각을 적극적으로 활용한 것이 템플릿 레이아웃이라고 할 수 있다. 이전 것을 이해했다면 템플릿 레이아웃도 쉽게 이해할 수 있다.

활용

템플릿 레이아웃의 경우, 모든 페이지에 공통으로 활용해야 할 부분이 있고 일부 페이지에서만 특별하게 추가해야하는 경우가 있을 때 이를 처리하는 것을 도와준다.

아래 예제는 <head> 태그에 css, js 등의 정보를 담아두고 각 페이지마다 필요한 부분이 있으면 추가하여 사용할 수 있도록 한다.

활용 - base.html

아래와 같이 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 가 들어가있다.
  • 여기서 보면 알 수 있는 것이 <head> 의 파라미터로 받는 두 가지에 th:replace 가 있다는 점 !

활용 - layoutMain.html

레이아웃을 활용할 메인 페이지는 아래와 같다. 템플릿 조각에서 이해한 부분을 바탕으로 이해하면 된다.

<!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}"> 이 두 개의 태그가 넘겨지게 된다.
  • 이렇게 하면 base.html의 <head th:fragment="common_header(title,links)"> 태그에 따라 첫 번째로 넘어오는 값은 title이라는 변수명으로, 두 번째로 넘어오는 값은 links라는 변수명에 저장된다고 생각한다.
  • <title th:replace="${title}">레이아웃 타이틀(head)</title> 부분에서 변수명 title이 사용되어 "${title}" 에 태그가 대입되어 넘겨진 태그로 치환된다.
  • <th:block th:replace="${links}"/> 또한 위와 동일하게 전달해준 두 개의 태그가 들어가게 된다.

결과

결과적으로 중간에는 공통으로 넣은 태그들은 동일하게 들어가게 되고, 파라미터로 넘겨준 태그들을 통해 태그가 바뀌어(replace), 아래와 같이 페이지가 출력되게 된다.

profile
안녕하세요. 백엔드 개발자가 되고 싶은 Kade 입니다.

0개의 댓글