본문 바로가기
개발일지/Spring

Thymeleaf(타임리프) 템플릿엔진 ?

by 꾸주니=^= 2025. 2. 6.

thymeleaf 로고

 

Thymeleaf(타임리프)는 Java 기반의 템플릿 엔진으로, Spring Boot와 함께 가장 많이 사용되는 뷰 템플릿 엔진 중 하나입니다.

HTML을 기반으로 하여 동적인 웹 페이지를 만들 수 있으며, 서버에서 데이터를 전달하여 이를 HTML 내에서 표현하는 방식으로 작동합니다.

 


1. Thymeleaf의 특징

1) 순수 HTML 파일을 그대로 열어볼 수 있음

Thymeleaf는 일반적인 HTML 파일로 작성되므로, 브라우저에서 직접 열어도 깨지지 않고 정상적인 HTML 페이지로 보입니다.
이는 JSP와 같은 템플릿 엔진과 비교했을 때 가장 큰 장점 중 하나입니다.

2) Spring Boot와의 강력한 통합 지원

Spring Boot에서 spring-boot-starter-thymeleaf를 추가하면 자동으로 Thymeleaf를 사용할 수 있도록 설정됩니다.
Spring의 Model 객체를 통해 데이터를 쉽게 전달할 수 있습니다.

3) 서버 사이드 렌더링(SSR) 지원

Thymeleaf는 서버에서 HTML을 렌더링한 후 클라이언트에 전송하는 방식이므로, SEO 최적화가 용이하며, 서버에서 데이터를 처리하여 화면을 그리는 것이 가능합니다.

4) 표준 HTML 속성 확장

Thymeleaf는 th:text, th:if, th:each  HTML 속성을 확장하여 동적인 데이터를 표현할 수 있도록 합니다.

5) 템플릿 재사용 가능

  • th:replace, th:insert 등을 사용하여 공통 레이아웃을 쉽게 적용할 수 있음
  • th:fragment 기능을 이용하면 컴포넌트처럼 HTML 블록을 재사용할 수 있음

 


2. Thymeleaf 기본 문법

Spring Boot와 함께 사용할 때, Thymeleaf는 HTML 파일 내에서 th:* 속성을 사용하여 데이터를 바인딩합니다.

1) 변수 출력 (th:text)

<p th:text="${message}">기본 텍스트</p>
  • ${message} 값이 Hello Thymeleaf!라면, 렌더링 결과:
<p>Hello Thymeleaf!</p>
  • th:text는 기존의 <p> 내부 텍스트를 대체합니다.

 

2) 값 설정 (th:value)

<input type="text" th:value="${username}" />
  • ${username} 값이 "John Doe"라면:
<input type="text" value="John Doe" />

 

3) 조건문 (th:if, th:unless)

<p th:if="${isLogin}">로그인 상태입니다.</p>
<p th:unless="${isLogin}">로그인이 필요합니다.</p>
  • isLogin이 true라면 "로그인 상태입니다."가 출력됨
  • false라면 "로그인이 필요합니다."가 출력됨

 

4) 반복문 (th:each)

<ul>
    <li th:each="user : ${users}" th:text="${user.name}"></li>
</ul>
  • users가 List<User>라면, 각 User 객체의 name 속성이 <li> 태그에 출력됨

 

5) URL 링크 (th:href)

<a th:href="@{/user/profile(id=${userId})}">프로필 보기</a>
  • userId가 100이라면:
<a href="/user/profile?id=100">프로필 보기</a>

 

6) 템플릿 레이아웃 사용

 th:replace (템플릿 대체)

<header th:replace="~{fragments/header}"></header>
  • fragments/header.html을 현재 페이지의 <header> 태그로 대체

 

 th:insert (템플릿 삽입)

<div th:insert="~{fragments/footer}"></div>
  • fragments/footer.html 내용을 <div> 내부에 삽입

 

 th:fragment (템플릿 조각 정의)

<!-- fragments/header.html -->
<div th:fragment="header">
    <h1>공통 헤더</h1>
</div>
  • 이를 <header th:replace="~{fragments/header}"></header>로 호출 가능

 


3. Thymeleaf와 Spring Boot 연동

1) Thymeleaf 의존성 추가

Spring Boot 프로젝트에서는 spring-boot-starter-thymeleaf를 추가하면 자동으로 Thymeleaf를 사용할 수 있습니다.

 

🛠 build.gradle에 의존성 추가 (Spring Boot 사용 시)

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}

 

2) Thymeleaf 설정 (application.properties)

spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
  • cache=false: 개발 중에는 캐시를 비활성화하여 변경 사항을 바로 반영
  • prefix: Thymeleaf 템플릿 파일의 기본 위치 (resources/templates/)
  • suffix: .html 확장자 사용

 

3) 컨트롤러에서 데이터 전달

@Controller
public class HomeController {
    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("message", "Hello Thymeleaf!");
        return "hello";  // templates/hello.html을 반환
    }
}
  • Model 객체를 사용하여 템플릿에 데이터를 전달할 수 있음.
  • return "hello"  src/main/resources/templates/hello.html 파일을 찾음.

 

4) hello.html (템플릿 파일)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf 예제</title>
</head>
<body>
    <h1 th:text="${message}">기본 메시지</h1>
</body>
</html>
  • message 값이 "Hello Thymeleaf!"이면:
<h1>Hello Thymeleaf!</h1>

 


4. Thymeleaf 활용 예제

📌 로그인 여부에 따른 화면 제어

<p th:if="${user != null}" th:text="|안녕하세요, ${user.name}님!|"></p>
<p th:unless="${user != null}">로그인이 필요합니다.</p>

 

📌 반복문을 활용한 테이블 출력

<table>
    <tr>
        <th>이름</th>
        <th>나이</th>
    </tr>
    <tr th:each="person : ${people}">
        <td th:text="${person.name}"></td>
        <td th:text="${person.age}"></td>
    </tr>
</table>

 


✔ Thymeleaf는 HTML 기반의 서버 사이드 템플릿 엔진으로, 브라우저에서도 볼 수 있는 순수 HTML 구조를 유지합니다.
 th:text, th:if, th:each 등의 속성을 활용하여 동적인 웹 페이지를 만들 수 있습니다.
✔ Spring Boot와의 자동 통합, 템플릿 재사용 기능(th:fragment) 등을 통해 유지보수성이 높습니다.
✔ 서버에서 데이터를 렌더링하여 SEO 최적화와 보안에도 유리합니다.

Spring Boot 기반의 웹 애플리케이션을 개발할 때 프론트엔드와 백엔드가 강하게 결합된 구조를 원한다면, Thymeleaf는 가장 적합한 선택지 중 하나입니다! 🚀