본문 바로가기
Etc/Thymeleaf

Thymeleaf - 템플릿 레이아웃

by HwaHyun 2023. 7. 25.

템플릿 레이아웃

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

 

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

 

TemplateController

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

 

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>

 

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>

 

 

코드 실행 결과

 

  • common_header(~{::title},~{::link}) 이 부분이 핵심이다.
    • ::title 은 현재 페이지의 title 태그들을 전달한다.
    • ::link 는 현재 페이지의 link 태그들을 전달한다.


결과

메인 타이틀이 전달한 부분으로 교체되었다.

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

 

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

'Etc > Thymeleaf' 카테고리의 다른 글

Thymeleaf - 템플릿 레이아웃(2)  (0) 2023.07.25
Thymeleaf - 템플릿 조각  (0) 2023.07.25
Thymeleaf - 자바스크립트 인라인  (0) 2023.07.25
Thymeleaf - 블록  (0) 2023.07.25
Thymeleaf - 주석  (0) 2023.07.25