본문 바로가기
개발공부 개발새발/etc

thymeleaf 레이아웃 설정하기 !

by 휴일이 2023. 3. 8.

타임리프로 중복 헤드/헤더/푸터를 손쉽게 설정해보자!

이것은 마치 like 객체지향

중복으로 계속 나오는 뷰를 한꺼번에 모아서

수정하기 안성맞춤으로 만든다

 

gradle 에서

implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'

얘를 추가해주면 된다

 

 

 

일단 폴더 구성

 

 

templates 폴더 하위에

* fragments

- head

- header

- footer

* layout

- default_layout

 

각 폴더와 파일을 만들어준다

 

 

head

일반적으로 우리가 헤드에 넣는 내용을 전부 넣으면 된다

html에서 <head></head>에 있는 내용 싹 다 긁어 넣는다

 

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<th:block th:fragment="headFragment">
  <head>
  여기에 헤드 내용
  </head>
</th:block>
</html>

 

나는 헤드에 들어가는 css 링크 경로 등이랑

<title>타이틀</title> 을 넣어주었다 ^0^/

 

<th:block th:fragment="헤드이름"> 으로 헤드 이름을 설정하는 것을 잊지 말자!

 

 

header

헤더는 말 그대로 헤더인데 중복되는 헤더를 넣으면 된다

예를 들어서 어느 페이지로 가던 상단에 떠있는 메뉴 바 같은 것!!

 

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<th:block th:fragment="headerFragment(param1)">
헤더 내용
</th:block>
</html>

 

<th:block th:fragment="헤더이름"> 을 잊지 말자!

참고로 헤더이름(param1) 은 파라미터인데

헤더에도 파라미터를 받아서 EL로 ${param1} 처럼 띄울 수 있다^0^/

 

 

 

footer

마지막으로 페이지 제일 아래 위치한 footer !

헤더와 동일하게 페이지에서 중복으로 띄우는 하단 바를 넣어준다

나는 지금 부트스트랩 테마를 써서 작업중이라서

부트스트랩 하단에 있는 js 경로 등도 함께 붙여넣어 주었다

 

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<th:block th:fragment="footerFragment">
푸터내용
</th:block>
</html>

 

<th:block th:fragment="푸터이름"> 역시 잊지 말자!

 

 

 

그 다음 레이아웃을 설정해줘야겠지?

나는 기본 레이아웃을 default_layout 이라는 이름으로 설정했다^0^/

 

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
  <th:block th:replace="fragments/head :: headFragment"></th:block>
<body>
<div>
  <th:block th:replace="fragments/header :: headerFragment('Header')"></th:block>
  <th:block layout:fragment="content"></th:block>
  <th:block th:replace="fragments/footer :: footerFragment"></th:block>
</div>
</body>
</html>

 

보면 xmlns:layout 을 써서 내가 레이아웃 기능을 사용할 것이다(얘가 레이아웃임) 이라고 명시해주었고

 

<th:block th:replace="폴더이름/헤더 :: 헤더이름('파라미터')"></th:block>

 

이런 느낌으로다가 내가 여기에 어떤 레이아웃을 넣을 것인지 명시해준다

 

<th:block layout:fragment="content"></th:block>

그리고 이건 content , 즉 안에 들어갈 내용이당

바디 내용은 이것이다 라고 말해주는 것

 

 

 

body(레이아웃을 사용할 html(타임리프))

 

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="layout/default_layout">
<th:block layout:fragment="content">
<body>
바디 내용
</body>
</th:block>
</html>

 

이런 식으로 바디 내용을 써주는데

얘가 바디(내용)라는 걸 명시해주기 위해

 

<th:block layout:fragment="content">

이 친구를 추가했다! 얘는 레이아웃에서 content 를 맡는다는 뜻

 

 

 

 

그래서 결국!!!결과는?

 

 

헤더 적용!

 

 

푸터 적용!(작업 덜 돼서 잘라서 올림 ㅠㅠ)

 

그리고 css 까지 제대로 나오는 것을 볼 수 있다^0^/

 

 

 

하...이거 하느라 벌써 두시다

얼른 자야징!!

728x90