타임리프(Thymeleaf) 마스터하기: HTML과 Java의 완벽한 조화

1. Thymeleaf란?

Thymeleaf(타임리프)는 Java 기반의 템플릿 엔진으로, HTML을 동적으로 렌더링하는 데 사용됩니다.

Spring Boot에서 가장 많이 사용되는 템플릿 엔진 중 하나로, JSP를 대체할 수 있는 강력한 기능을 제공합니다.

 

주요 특징

  • HTML 친화적 : HTML 파일을 그대로 유지하면서 서버에서 동적으로 렌더링할 수 있음
  • 서버-클라이언트 양방향 지원 : 정적 HTML로도 동작하며, 서버에서 데이터 바인딩 가능
  • Spring과의 강력한 통합 : Spring MVC와 쉽게 연동할 수 있으며, Model 데이터를 HTML에 매핑하기 용이함
  • 템플릿 재사용 가능 : th:replaceth:fragment 등을 이용해 HTML 요소를 재사용할 수 있음

2. Thymeleaf 기본 문법

텍스트 출력

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

message 변수의 값을 태그 안에 출력합니다.

 

속성 변경

<a th:href="@{/home}">홈으로 이동</a>

 

조건문

<p th:if="${user != null}">사용자 정보: <span th:text="${user.name}"></span></p>

 

반복문

<ul>
    <li th:each="item : ${items}" th:text="${item}"></li>
</ul>

3. Spring Boot 프로젝트에서 Thymeleaf 적용

Spring Boot 프로젝트 설정

1. spring-boot-starter-thymeleaf 의존성 추가

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

 

2. Controller에서 데이터 전달

@Controller
public class HomeController {
    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("message", "Hello, Thymeleaf!");
        return "index";
    }
}

 

3. index.html 템플릿 생성

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf Example</title>
</head>
<body>
    <h1 th:text="${message}">기본 메시지</h1>
</body>
</html>

4. 고급 기능 활용

Fragment (템플릿 재사용)

<!-- header.html -->
<header th:fragment="header">
    <h1>공통 헤더</h1>
</header>

<!-- index.html -->
<div th:replace="header :: header"></div>

 

Spring Security와 Thymeleaf 연동

<div sec:authorize="isAuthenticated()">
    <p>로그인 사용자: <span sec:authentication="name"></span></p>
</div>

 

국제화(i18n) 지원

1. messages.properties 파일 생성

welcome.message=환영합니다!

 

2. 템플릿에서 메시지 출력

<p th:text="#{welcome.message}"></p>

5. 실무에서의 Thymeleaf 활용 팁

  • 템플릿 분할 : th:fragment를 적극 활용해 템플릿 모듈화하기
  • 성능 최적화 : HTML 구조를 단순화하고, 불필요한 반복문 줄이기
  • AJAX와 조합: Thymeleaf는 정적인 HTML을 관리하고, 동적인 요소는 AJAX를 활용하면 더욱 효과적임

 

이제 타임리프를 활용하여 효율적이고 유지보수하기 쉬운 템플릿을 만들어보세요!