템플릿 레이아웃은 기존의 템플릿 조각에서 코드의 일부 조각을 가져와 사용했던 것을 확장하여, 레이아웃에 넘겨 사용하는 것이다.

 

그중 하나의 예로 <head> 태그에 공통으로 사용을 희망하는 css나 javascript 등의 속성 및 정보들을 한곳에 모아두고 사용하며, 페이지에 따라 필요로 하는 추가적인 정보 사용을 위해 다음과 같이 설정한다.

 

 

1. 일부 - <head>

Controller

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

 

Layout.HTML

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

 

Main.HTML

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

 

결과

<head>
	<title>메인 타이틀</title>
    
	<!-- 공통 -->
	<link rel="stylesheet" type="text/css" media="all" href="/css/awesomeapp.css">
	<link rel="shortcut icon" href="/images/favicon.ico">
	<script type="text/javascript" src="/sh/scripts/codebase.js"></script>
    
	<!-- 추가 -->
	<link rel="stylesheet" href="/css/bootstrap.min.css">
	<link rel="stylesheet" href="/themes/smoothness/jquery-ui.css">
</head>

 

th:replace="template/layout/base :: common_header(~{::title},~{::link})
  • ~{::title} : 현재 페이지의 <title> 태그 전달
  • ~{::link} : 현재 페이지의 <link> 태그 전달
※ 결과
  -  공통 파트의 유지
  -  추가 파트에 layout.html에서 전달된 태그들이 전달되어 추가

 

 

 

2. 전체 <html>

Controller

@GetMapping("/layoutExtend")
public String layoutExtends() {
	return "template/layoutExtend/layoutExtendMain";
}

 

Layout.HTML

<!DOCTYPE html>
<html th:fragment="layout (title, content)" xmlns:th="http://www.thymeleaf.org">
<head>
	<title th:replace="${title}">레이아웃 타이틀</title>
</head>
<body>
<h1>레이아웃 H1</h1>
<div th:replace="${content}">
	<p>레이아웃 컨텐츠</p>
</div>
<footer>
 레이아웃 푸터
</footer>
</body>
</html>

 

Main.HTML

<!DOCTYPE html>
<html th:replace="~{template/layoutExtend/layoutFile :: layout(~{::title}, ~{::section})}"
 xmlns:th="http://www.thymeleaf.org">
<head>
	<title>메인 페이지 타이틀</title>
</head>
<body>
<section>
	<p>메인 페이지 컨텐츠</p>
	<div>메인 페이지 포함 내용</div>
</section>
</body>
</html>

 

결과

<!DOCTYPE html>
<html>
<head>
<title>메인 페이지 타이틀</title>
</head>
<body>
<h1>레이아웃 H1</h1>
<section>
<p>메인 페이지 컨텐츠</p>
<div>메인 페이지 포함 내용</div>
</section>
<footer>
레이아웃 푸터
</footer>
</body>
</html>

 

※ 결과
  -  layout.html의 <html> 태그에 th:fragment 속성 정의
  -  main.html의 <html> 자체를 th:replace 를 사용하여 필요 내용을 부분적으로 전달하며 사용

 

 

 

 

 

 

'Thymeleaf' 카테고리의 다른 글

[Thymeleaf] 입력 폼 처리  (0) 2023.03.10
[Thymeleaf] 타임리프 스프링 통합  (0) 2023.03.10
[Thymeleaf] 템플릿 조각  (0) 2023.02.01
[Thymeleaf] 자바스크립트 인라인  (0) 2023.01.31
[Thymeleaf] 블록  (0) 2023.01.30

+ Recent posts