쌓고 쌓다

로그인 여부에 따라 헤더(네비게이션) 바꾸기 - 레이아웃 본문

프로그래밍/thymeleaf

로그인 여부에 따라 헤더(네비게이션) 바꾸기 - 레이아웃

승민아 2023. 9. 28. 16:56

기존 템플릿 조각을 불러와서불러와서

매번 조각을 부르는 코드를 작성하기에는 효율적이지 않다.

공통적인 영역을 사용하는데 매번 코드를 작성하는 것 보단.

공통적인 영역을 만들어 놓고. 바뀌는 부분(컨텐츠)에만 코드를 집어 넣는것이 좋은 방법이다.

 

defaultLayout.html

<!DOCTYPE html>
<html lang="en" th:fragment="layout (title, content)" xmlns:th="http://thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title th:replace="${title}">Title</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<th:block th:replace="~{template/fragment/header :: headerFragment}">
    <p>헤더(navigation var)</p>
</th:block>

<th:block th:replace="${content}">
    <p>레이아웃 컨텐츠</p>
</th:block>


<script src="/js/kakaoButton.js"></script> <!-- login, logout 버튼 처리 -->
<script src="/js/bootstrap.min.js"></script>
</body>
</html>

로그인 여부에 따라 헤더 부분만 달리하길 원하기에

헤더 부분의 코드는 템플릿 조각인 "headerFragment"를 가져오기로 작성했다.

 

또한 다른 페이지에서 보내온 컨텐츠는 content로 받아 replace를 한다.

 

fragment와 replace 사용 방법에 대한 과정은 앞선 게시글에서 설명했으므로

과정에 대해서만 알아보자.

 

<html lang="en" th:fragment="layout (title, content)" xmlns:th="http://thymeleaf.org">

<html>에 th:fragment 속성을 가진다.

이 defaultLayout 파일 html을 기본으로하여

다른 곳에서 전달한 title, content를 받아 끼워 넣는 방식이라고 이해하면 된다.

컨텐츠를 끼워 넣은 defaultLayout.html의 <html> 태그 전체를 다른 페이지에서 사용한다고 생각하면 된다.

 

그럼 다른 곳에서 title, content를 전달하는 방법을 알아보자.

 

home.html

<!DOCTYPE html>
<html lang="en" th:replace="~{template/defaultLayout :: layout(~{::title}, ~{::section})}"
      xmlns:th="http://thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<section>
    <h1>Home</h1>
</section>
<script src="/js/bootstrap.min.js"></script>
</body>
</html>

역시 html에 th:replace 속성을 사용한다.

th:replace 속성으로 변경할 title 태그와 section 태그(content)를 넘겨 replace하면

defaultLayout에 현재 homt.html의 title과 section가 넣어진 defaultLayout.html로 replace 할 수 있다.

  • th:replace="~{template/defaultLayout :: layout(~{::title}, ~{::section})}"
    • ::title -> 현재 페이지의 title 태그들을 전달
    • ::section -> 현재 페이지의 section 태그들을 전달

 

결국 home.html은 필요한 title과 content를 넘김으로써

title, content가 끼워진 defaultLayout.html로 replace 할 수 있는 것이다.

Comments