Programing/JavaScript

Thymeleaf layout 적용 방법

리커니 2022. 5. 19.
반응형

Thymeleaf layout 적용 방법

 

Spec

springboot 2.6.7

thymeleaf 3.0.15

 

Apache tiles와 같은 기능을 해주는 Thymeleaf layout을 적용하는 방법을 알아보겠습니다.

layout은 별도의 설정파일 없이 .html 코드만 수정하면 적용이 가능하기 때문에 tiles 에 비해 적용이 쉽습니다.

 

Dependency 추가 (gradle)

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect'

 

layout을 사용하기 위해서는 thymeleaf-layout-dialect 의존성 주입이 필요합니다.

위와 같이 의존성 주입을 해줍니다.

 

thymeleaf html기본 패키지인 src/main/resources/templates 에 layout 패키지를 추가하고 아래와 같이

4개의 .html 파일을 생성합니다.

 

 

config.html

<!DOCTYPE html>
<html>
<body>
<th:block th:fragment="config">
	<link rel="stylesheet" th:href="@{/css/common.css}"/>
	<script type="text/javascript" th:src="@{/js/aljjabaegi-2.0.2.js}"></script>
</th:block>
</body>
</html>

페이지내에서 공통적으로 사용하는 js나 css 파일을 설정하는 역할을 합니다.

resource 파일의 기본 경로는 src/main/resources/static/ 입니다.

 

header.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<th:block th:fragment="header">
	<!-- 여기에 header 부분 HTML 구성 -->
	================= header =================
</th:block>
</html>

페이지 내 header 영역 표출 부분입니다.

 

footer.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<th:block th:fragment=footer>
	<!-- 여기에 footer 부분 HTML 구성 -->
	================= footer =================
</th:block>
</html>

페이지 내 footer 영역 표출 부분입니다.

 

layout.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" 
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>layout</title>
<th:bloc th:replace="layout/config::config"></th:bloc>
</head>
<body>
	<th:bloc th:replace="layout/header::header"></th:bloc>
	<th:bloc layout:fragment="content"></th:bloc>
	<th:bloc th:replace="layout/footer::footer"></th:bloc>
</body>
</html>

페이지 내 layout을 구성하는 부분입니다.

th:replace 는 태그 전체를 교체해 주는 역할을 합니다. 

<th:bloc th:replace="layout/config::config"></th:bloc>

 

위의 코드를 예를 들면 위 태그가 들어간 영역을 layout/config 파일의 fragment가 config로 설정된 부분과 바꾸겠다는 의미가 됩니다.

 

layout:fragment 는 layout을 사용하는 fragment의 내용을 불러오겠다는 의미 입니다.

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

layout을 사용하는 페이지에서 fragment가 content로 설정된 부분의 내용을 불러게 됩니다.

이제 hello.html 파일을 생성하여 layout 구성을 잡아보겠습니다.

 

hello.html

<!DOCTYPE html>
<html lang="en" layout:decorate="~{layout/layout}">
<th:block layout:fragment="content">
	<h1>HELLO~~~~~~~</h1>
</th:block>
</html>

layout:decorate를 써서 해당 layout을 사용하겠다 선언하고

layout:fragment를 content로 설정하여 layout의 content 영역에 추가될 html을 작성합니다.

그럼 위의 layout.html 파일 내 layout:fragment="content" 가 설정된 부분에 hello.html 의 layout:fragment="content"가 불러와지게 됩니다.

 

그럼 hello.html 페이지를 불러와 보겠습니다.

 

 

layout에 구성된 내용에 맞게 페이지가 표출되는 것을 확인하실 수 있습니다.

 

 

반응형

댓글

💲 추천 글