BackEnd/Thymeleaf

[Thymeleaf] 레이아웃

샤아이인 2022. 1. 30.

인프런 김영한님의 Spring강의에서 공부한것을 올리며, Thymeleaf의 경우 unit 단위로 공부후 각각 정리하는 글을 작성하겠습니다.

 

레이아웃

이전 템플릿 조각에서는 코드 조각을 갖고와서 내가 원하는 부분에 추가하는 방식 이였다면 (내 코드 <-- 공통 부분)

이번 템플릿 레이아웃 에서는 코드 조각을 레이아웃에 넘겨 사용하는 방법에 대하여 알아보자 (내 코드 --> 공통 부분)

 

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

 

우선 컨트롤러와 뷰 코드를 살펴봅시다.

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

base (공통 부분)

<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>
 

layoutMain(내 코드)

<!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>
 

결과는 다음과 같습니다.

우선 http://localhost:8080/template/layout 에 접속하면 컨트롤러가 작동하여 "template/layout/layoutMain" 의 뷰로 이동하게 된다.

layoutMain 에서는 <head th:replace="template/layout/base :: common_header(~{::title},~{::link})"> 로 인하여 head 부분을replace하기위해 공통부분인 base를 끌어온다.

 

이때! layoutMain 에서의 common_header(~{::title},~{::link}) 이 부분이 핵심이다.

layoutMain에서 교체할 head를 base의 head부분으로 통으로 바꿀껀데, title, link는 layoutMain에서 받은 정보를 통해 head 부분을 바꾸겠다는 의미이다.

 

::title 은 현재 페이지(layoutMain)의 title 태그들을 base로 전달한다.

<title>메인 타이틀</title>
 

::link 는 현재 페이지(layoutMain)의 link 태그들을 base로 전달한다.

<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">
 

이렇게 전달되면 위의 결과물처럼 base파일 안에 공통부분은 유지가 되면서,

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

또한 link부분도 전달한 link들이 포함되었다.

 

레이아웃 파일(base)을 기본으로 하고 여기에 필요한 내용을 전달해서 부분부분 변경하는 것으로 이해하면 된다.

 

<html> 자체를 th:replace 를 사용해서 변경할수도 있다.

결국 layoutFile.html 에 필요한 내용을 전달하면서 <base.html> 자체를 layoutFile.html 로 변경하는 것 이다.

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

[Thymeleaf] 체크 박스  (0) 2022.01.30
[Thymeleaf] 입력 폼 처리  (0) 2022.01.30
[Thymeleaf] 템플릿 조각  (0) 2022.01.29
[Thymeleaf] 자바스크립트 인라인  (0) 2022.01.28
[Thymeleaf] 블록  (0) 2022.01.28

댓글