2 분 소요


템플릿 조각

웹 페이지를 개발할 때는 상/하단 영역, 좌측 카테고리 등 공통 영역이 있다. 이런 부분을 코드를 복사해서 사용한다면 변경시 모두 수정해야 하므로 비효율적이다. 타임리프는 이런 문제를 해결하기 위해 템플릿 조각과 레이아웃 기능을 지원한다.

템플릿 조각

@GetMapping("/fragment")
    public String template() {
    return "template/fragment/fragmentMain";
}

footer.html

<footer th:fragment="copy">
    푸터 자리 입니다.
</footer>

<footer th:fragment="copyParam (param1, param2)">
    <p>파라미터 자리 입니다.</p>
    <p th:text="${param1}"></p>
    <p th:text="${param2}"></p>
</footer>

fragmentMain.html

<!-- 부분 포함 insert -->
<div th:insert="~{template/fragment/footer :: copy}"></div>

<!-- 부분 포함 replace -->
<div th:replace="~{template/fragment/footer :: copy}"></div>

<!-- 부분 포함 단순 표현식 -->
<div th:replace="template/fragment/footer :: copy"></div>

<!-- 파라미터 사용 -->
<div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터2')}"></div>

template/fragment/footer :: copy
template/fragment/footer.html템플릿에 있는 th:fragment="copy"부분을 템플릿 조각으로 가져와서 사용한다는 의미.

부분 포함 insert
<div th:insert="~{template/fragment/footer :: copy}"></div>

<div>
<footer>
푸터 자리 입니다.
</footer>
</div>

th:insert를 사용하면 현재 태그(div) 내부에 추가한다.

부분 포함 replace
<div th:replace="~{template/fragment/footer :: copy}"></div>

<h2>부분 포함 replace</h2>
<footer>
푸터 자리 입니다.
</footer>

th:replace를 사용하면 현재 태그(div)를 대체한다.

부분 포함 단순 표현식
~{...}를 사용하는 것이 원칙이지만 템플릿 조각을 사용하는 코드가 단순하면 생략할 수 있다.

파라미터 사용

<footer>
<p>파라미터 자리 입니다.</p>
<p>데이터1</p>
<p>데이터2</p>
</footer>


템플릿 레이아웃1

Ex) <head>에 공통으로 사용하는 css, javascript같은 정보들을 한 곳에 모아두고 공통으로 사용하지만, 각 페이지마다 필요한 정보를 더 추가해서 사용하고 싶을 때 다음과 같은 방법을 사용한다.

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

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

layoutMain.html

<html xmlns:th="http://www.thymeleaf.org">
<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>
<body>
메인 컨텐츠
</body>
</html>

결과

<html>
<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>
<body>
메인 컨텐츠
</body>
</html>
  • 핵심 코드 : common_header(~{::title},~{::link})
    • ::title은 현재 페이지의 title 태그들을 전달한다.
    • ::link는 현재 페이지의 link 태그들을 전달한다.
  • 공통 부분은 그대로 유지되고, 추가 부분에 전달한 <link>들이 포함되었다.


템플릿 레이아웃2

레이아웃 확장

<head>정도에만 적용하는 것이 아닌, <html> 전체에 적용할 수도 있다.

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

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

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

결과

<html>
<head>
    <title>메인 페이지 타이틀</title>
</head>

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

layoutFile.html을 보면 <html>th:fragment 속성이 정의되어 있어, 이 레이아웃 파일을 기본으로 하고 여기에 필요한 내용을 전달해서 부분부분 변경하는 것이다.

layoutExtendMain.html은 현재 페이지인데, <html> 자체를 th:replace를 사용해서 layoutFile.html에 필요한 내용을 전달하면서 <html>자체를 layoutFile.html로 변경한다.


<출처 : 인프런 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술(김영한)>

댓글남기기