TIL

230317 [Spring, thymeleaf] (layout)

하차모 2023. 3. 17. 17:26

1. Controller

package com.study.test.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class BoardController {

	//'localhost:8081/list'로 들어오는 http get 요청을 받음
	@GetMapping("/list")
	public String boardList() {
    	//src/main/resources/templates 파일을 기준으로 "" 안의 이름을 가진 html 파일로 이동
		return "content/board_list";
	}
}

 

2. board_list.html : 본문(내용)에 들어가는 파일

<!DOCTYPE html>
<html 	xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
	layout:decorate="~{fragment/layout}">
        <!-- 레이아웃 설정을 위한 라이브러리 설정 --> 
        <!-- fragment 폴더 안의 layout html 파일과 함께 열림 --> 


<th:block layout:fragment="content_css">
	 <!-- 해당 페이지의 외부 css 파일 경로 설정 --> 
	<link rel="stylesheet" href="/css/test.css">
</th:block>

<th:block layout:fragment="content">
	<!-- 본문 내용 -->
	<div class="testDiv">본문 내용</div>
</th:block>

<th:block layout:fragment="content_js">
	<!-- 해당 페이지의 외부 javascript 파일 경로 설정 --> 
	<script type="text/javascript" src="/js/test.js"></script>
</th:block>

</html>

 

3. layout.html : 전체적인 레이아웃

<!DOCTYPE html>
<html 	xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<!-- css 설정 -->
<th:block layout:fragment="content_css"></th:block>

</head>
<body>
	<div>
		<!-- 헤더 -->
		<div>
			<th:block th:replace="~{fragment/header::headerFragment}"></th:block>
		</div>
		
		<!-- 본문 -->
		<div>
			<th:block layout:fragment="content"></th:block>
		</div>
	</div>
	
<!-- javascript 설정 -->
<th:block layout:fragment="content_js"></th:block>

</body>
</html>

 

+) th:replace -> 해당 태그 전체를 지정한 템플릿 조각으로 교체함.

<th:block th:replace="~{템플릿 조각 경로::조각명}"></th:block>

 

+)layout:fragment -> layout을 사용하는 html 페이지에서 " " 안의 이름을 가진 fragment을 가져옴. 변하는 내용일 때

<th:block layout:fragment="조각명"></th:block>

 

4. header.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<th:block th:fragment='headerFragment'>
	<div>header 파일</div>
</th:block>

</html>

 

5. test.css

@charset "UTF-8";

.testDiv{
	background-color: aqua;
}

 

6. test.js

alert('외부 js 파일이 연결되었습니다.');