템플릿 레이아웃1

shinyeongwoon·2022년 12월 31일
0

tymeleaf

목록 보기
16/24

템플릿 레이아웃

이전에는 일부 코드 조각을 가지고와서 사용했다면, 이번에는 개념을 더 확장해서 코드 조각을 레이아웃에 넘겨 사용하는 방법에 대해 알아보자

예를 들어 <head>에 공통으로 사용하는 css,js같은 정보들이 있는데,
이러한 공통 정보들을 한 곳에 모아두고, 공통으로 사용하지만, 각 페이지마다 필요한 정보를 더 추가해서 사용하고 싶다면 다음과 같이 사용할 수 있다.

@GetMapping("/layout")
public String layout(){
	return "template/layout/layoutMain";
}

/resources/templates/template/layout/base.html

<html xmlns:th="http://www.thymeleaf.org">

<head th:fragment="common_header(title,links)">

  <title th:replace="${title}">레이아웃 타이틀</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>

/resources/templates/template/layout/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>

결과

<!DOCTYPE html>
<html>
<head>
<title>메인 타이틀</title> <!-- 공통 -->
  <link rel="stylesheet" type="text/css" media="all" href="/css/awesomeapp.css">
  <link rel="shortcut icon" href="/images/favicon.ico">
  <script type="text/javascript" src="/sh/scripts/codebase.js"></script>
<!-- 추가 -->
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/themes/smoothness/jquery-ui.css">
</head> <body> 메인 컨텐츠 </body> </html>

common_header(~{::title},~{::link}) 이 부분이 핵심이다.

  • ::title은 현재 페이지의 title 태그들을 전달한다.
  • ::link는 현재 페이지의 link 태그들은 전달한다.

결과를 보자.

메인 타이틀이 전달한 부분으로 교체되었다.
공통 부분은 그대로 유지되고, 추가 부분에 전달한 <link>들이 포함된 것을 확인할 수 있다.

이 방식은 사실 앞서 배운 코드 조각을 조금 더 적극적으로 사용하는 방식이다.
쉽게 이야기해서 레이아웃 개념을 두고, 그 레이아웃에 필요한 코드 조각을 전달해서 완성하는 것으로 이해하면 된다.

0개의 댓글