SpringBoot

"Thymeleaf란? Spring Boot와 함께하는 강력한 템플릿 엔진"

노아입니다 2025. 3. 26. 14:14

Thymeleaf란?

Thymeleaf는 Java 기반의 서버 사이드 템플릿 엔진으로, HTML을 동적으로 생성하는 데 최적화된 도구입니다. Spring Boot와 자연스럽게 통합되어 템플릿 렌더링을 간편하게 처리할 수 있으며, HTML 파일을 그대로 유지하면서 동적 웹 페이지를 쉽게 구현할 수 있습니다.

Thymeleaf의 주요 특징

  1. HTML 친화적
    • Thymeleaf는 기존 HTML 문법을 그대로 유지하면서 동적 콘텐츠를 삽입할 수 있습니다. 따라서 디자이너와 개발자가 협업하기 용이합니다.
  2. Spring Boot와 완벽한 통합
    • Spring Boot의 View Resolver를 통해 자동으로 템플릿을 찾고 렌더링합니다.
  3. 표현식 지원
    • 변수 출력, 조건문, 반복문 등의 기능을 제공하여 다양한 데이터 바인딩이 가능합니다.
  4. 템플릿 모드 지원
    • HTML, XML, JavaScript, CSS 등의 다양한 템플릿 모드를 지원합니다.
  5. 확장성
    • 사용자 정의 확장 기능을 통해 템플릿 엔진을 커스터마이징할 수 있습니다.

Thymeleaf의 기본 문법

1. 변수 표현식

Thymeleaf에서는 ${} 구문을 사용하여 모델 데이터를 바인딩할 수 있습니다.

<p th:text="${message}">기본 텍스트</p>

2. 조건문

th:if th:unless를 사용하여 조건부 렌더링이 가능합니다.

<p th:if="${isAdmin}">관리자 계정입니다.</p>
<p th:unless="${isAdmin}">일반 사용자 계정입니다.</p>

3. 반복문

th:each를 사용하여 리스트 데이터를 순회할 수 있습니다.

<ul>
    <li th:each="user : ${users}" th:text="${user.name}"></li>
</ul>

4. URL 링크 처리

@{} 표현식을 사용하여 동적으로 URL을 생성할 수 있습니다.

<a th:href="@{/users/{id}(id=${user.id})}">사용자 상세보기</a>

5. 폼 데이터 바인딩

Thymeleaf는 Spring MVC의 @ModelAttribute와 함께 사용할 수 있습니다.

<form th:action="@{/users}" th:object="${user}" method="post">
    <input type="text" th:field="*{name}" />
    <button type="submit">저장</button>
</form>

Spring Boot와 Thymeleaf 통합하기

Thymeleaf를 Spring Boot 프로젝트에 적용하려면 spring-boot-starter-thymeleaf 의존성을 추가해야 합니다.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

또한 application.properties에서 템플릿 위치를 설정할 수 있습니다.

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

Thymeleaf를 활용한 CRUD 예제

Thymeleaf를 사용하여 간단한 CRUD 애플리케이션을 만들어볼 수 있습니다. 예를 들어, 직원 관리 시스템을 구축해보겠습니다.

1. 직원 목록 템플릿 (employee-list.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>직원 목록</title>
</head>
<body>
    <h1>직원 목록</h1>
    <table>
        <tr>
            <th>ID</th>
            <th>이름</th>
            <th>이메일</th>
        </tr>
        <tr th:each="employee : ${employees}">
            <td th:text="${employee.id}"></td>
            <td th:text="${employee.name}"></td>
            <td th:text="${employee.email}"></td>
        </tr>
    </table>
    <a href="/employees/add">직원 추가</a>
</body>
</html>

결론

Thymeleaf는 직관적이고 강력한 템플릿 엔진으로, Spring Boot와 함께 사용할 때 뛰어난 생산성을 제공합니다. HTML 기반의 자연스러운 템플릿 시스템을 활용하여 유지보수와 협업이 용이하며, 다양한 표현식을 통해 동적인 웹 페이지를 쉽게 구축할 수 있습니다. 앞으로 Thymeleaf를 활용하여 더욱 다양한 프로젝트를 개발해보세요!

참고 자료