Thymeleaf는 크게 2가지 형태로 사용할 수 있음
1. JSP의 include와 같이 특정 부분을 외부 혹은 내부에서 가져와 포함
2. 특정한 부분을 파라미터로 전달해서 내용에 포함하는 형태
include와 layout의 차이
include 방식 처리
th:insert
: 바깥의 태그는 유지하되, 추가되는 방식th:replace
: 기존의 내용 완전히 대체
'/resource/templates/fragments/' 경로 안에 화면의 각 구성이 될 조각들을 'th:fragement'라는 속성으로 표현
- fragment1.html ( ... /resource/templates/fragments/fragment1.html)
<div th:fragment="part1">
<h2>Part 1</h2>
</div>
<div th:fragment="part2">
<h2>Part 2</h2>
</div>
<div th:fragment="part3">
<h2>Part 3</h2>
</div>
- exLayout1.html ( ... /resource/templates/sample/exLayout1.html)
<body>
<h1>Fragment Test</h1>
<h1>Layout 1 - 1</h1>
<div th:replace="~{/fragments/fragment1 :: part1}"></div> <!--replace는 쌍따옴표 안의 내용이 들어감-->
<h1>Layout 1 - 2</h1>
<div th:insert="~{/fragments/fragment1 :: part2}"></div>
<h1>Layout 1 - 3</h1>
<th:block th:replace="~{/fragments/fragment1 :: part3}"></th:block> <!--th:block은 모든 내용이 들어감-->
</body>
- 화면
파라미터 방식 처리
타임리프에서는 특정 태그를 파라미터처럼 전달해서 th:fragment 에서 활용할 수 있음
- fragment3.html ( ... /resource/templates/fragments/fragment1.html)
<div th:fragment="target(first, second)">
<style>
.c1 {
background-color: red;
}
.c2 {
background-color: blue;
}
</style>
<div class = "c1">
<th:block th:replace="${first}"></th:block>
</div>
<div class = "c2">
<th:block th:replace="${second}"></th:block>
</div>
</div>
- exLayout2.html ( ... /resource/templates/sample/exLayout1.html)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<th:block th:replace="~{/fragments/fragment3:: target(~{this:: #ulFirst}, ~{this:: #ulSecond} )}">
<ul id="ulFirst">
<li>AAA</li>
<li>BBB</li>
<li>CCC</li>
</ul>
<ul id="ulSecond">
<li>111</li>
<li>222</li>
<li>333</li>
</ul>
</th:block>
* this:: #ulFirst는 CSS의 id 선택자를 의미함. this는 현재 페이지를 의미할 때 사용하며, 생략이 가능함
- 화면
'WEB > Back-end' 카테고리의 다른 글
@ManyToOne와 @OneToMany(SpringBoot) (0) | 2024.10.15 |
---|---|
Thymeleaf 레이아웃 템플릿 (SpringBoot) (0) | 2024.08.23 |
Thymeleaf 기본(SpringBoot) (0) | 2024.07.30 |
Query Method, @Query, Querydsl(SpringBoot) (0) | 2024.07.30 |
(SQL) 숫자데이터 가공 함수 (0) | 2024.07.29 |