본문 바로가기
Spring Boot

230213 Spring Boot Thymeleaf 문법 -include

타임리프의 include 방식

(jsp header footer 가져오는 그 방식)

  • ~{경로}
    +)경로는 /면 절대경로, ./면 상대경로
  • 조각내는 부분
    th:fragment="part1"
  • 가져올땐
    th:replace="~{/경로::part1}"

"이때, fragment가 replace로 오는 것!"

 

 

Controller

//타임리프 include
@GetMapping("/ex06")
public String ex06() {
	return "view/ex06";
}

//타임리프 템플릿 모형 사용하기
@GetMapping("/ex07")
public String ex07() {
	return "view/ex07";
}

 

 

ex06.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	
	<h3>타임리프 include</h3>	
	
	<!-- fragment를 가져오기 ~{경로::가져올 이름} -->
	<div th:replace="~{/include/layout01::part1}"></div>
	
	<th:block th:replace="~{/include/layout01::part2}"></th:block>
	
	<!-- 파일을 통째로 가져오려면 ~{경로} -->
	<th:block th:replace="~{/include/layout02}"></th:block>
	
	
</body>
</html>

 

 

layout01.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<div th:fragment="part1">
		<h3>프래그먼트1</h3>
	</div>
	
	<div th:fragment="part2">
		<h3>프래그먼트2</h3>
	</div>

</body>
</html>

1.태그 자체가 통째로 대체된다고 생각하면 된다.

 

 

 

layout02.html

<header>
	<nav>
		<ul>
			<li><a href="#">메뉴</a></li>
			<li><a href="#">메뉴</a></li>
			<li><a href="#">메뉴</a></li>
			<li><a href="#">메뉴</a></li>
		</ul>
	</nav>
</header>

2.파일을 통째로 가져오려면 th:replace="~{경로}"를 하면 된다.

경로 확인. layout경로가 아니다. 화면경로는 replace가 있는 ex06이다.

 

 



3.템플릿 구현

 

layout03.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymleaf.org">
<th:block  th:fragment="함수(section)">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	
	<header>
		공통 템플릿 헤더
	</header>
	
	
	<section th:replace="${section}">
				
	</section>
	
	
	
	<footer>
		공통 템플릿 푸터
	</footer>
	
</body>
</th:block>
</html>

 

 

ex07.html

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


<!-- ~{파일경로::템플릿함수(~{::선택자})} -->
<th:block th:replace="~{/include/layout03::함수( ~{::#first} )}">

	<div id="first">
		아이디 선택자 #
	</div>
	
	<div class="second">
		클래스 선택자 .
	</div>
	
	
	
</th:block>

<script>
	console.log("이 파일에서만 사용");
</script>
</html>

해당 파일에서만 사용하려는 script는 th:replace가 있는 블럭 밖에다가 선언해야 한다.

 

 

마찬가지로 경로는 layout이 아닌 ex07이다.

 

 

사용방법이 특이한데,

-공용부분에 th:fragment="함수명(매개변수)"와 공용으로 쓸 부분에 th:replace="${매개변수}"를 사용,

-공용부분에 넣을 곳을 <th:block th:replace="~{/경로::함수명(~{::#아이디 or .클래스})}">로 감싼다.

-이때, 파일경로는 생략하면 현재 파일 자체가 된다.

-#아이디나 .클래스로 가져올 때, 해당태그 위나 아래에 내용이 있으면 화면에 포함되게 된다. 따라서 <html>태그 바로 아래와 </html>위에서 감싼다.

-개별적으로 사용할 script나 link 등은 공용파일과 합쳐졌을 때 중첩될 가능성이 있다.

따라서 보통 공용으로 사용할 부분의 js/css/img등을 위에 선언하고 개별적인것들은 해당파일의 </th:block>아래에 선언한다.