Spring
[Spring] Thymeleaf(타임리프)란?
s_ih_yun
2025. 9. 8. 01:07
728x90

1. Thymeleaf 란?
- HTML 파일에서 동적으로 데이터를 넣어주는 템플릿 엔진
- HTML과 Java를 연결해주는 역할
- Java 기반 템플릿 엔진 → 주로 Java(Spring Boot)에서 사용된다
- Spring MVC 패턴에서 V(View)에 해당하는 화면을 구현할 때 사용
- 아래 사진처럼 return “viewname”의 View를 구현

2. Spring에서 Thymeleaf 사용하기
2.1. 의존성 추가
- build.gradle : 의존성 추가
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
...
}
- [자동] application.properties
- 의존성을 추가하면 아래 코드가 자동으로 추가된다
- Thymeleaf가 기본으로 사용될 경로 : src/main/resources/templates
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
2.2. HTML 태그 추가
- Thymeleaf를 사용할 HTML파일에 태그를 수정
<html xmlns:th="http://www.thymeleaf.org">
3. Thymeleaf 기본 문법
- html 태그 속성에 [th:] 접두사가 붙은 속성을 사용하여 thymeleaf 문법 사용 가능
- 기본적인 문법
| 표현 | 설명 | 예시 |
| ${…} | Controller에서 전달한 Model 속성 값 참조 | ${student.name} |
| *{…} | 현재 객체의 속성을 간단하게 접근 (주로 th:object가 설정된 경우) |
<tr th:object="${student}"> <td th:text="*{id}"></td> </tr> (student.id를 의미) |
| #{…} | messages.properties 같은 외부 자원에서 값을 가져올 때 사용 |
#{id} (messages.properties 파일에 id=학생이 정의되어 있으면 학생으로 출력) |
| @{…} | URL을 동적으로 생성 | @{https://www.naver.com} |
| ~{…} | 프래그먼트 템플릿을 포함할 때 | ~{fragments/header} (fragments/header.html을 포함) |
| ${…} + ${…} | 텍스트 단순 결합 | ${id} + ${name} |
| |… ${…} … ${…}| | 리터럴 대체 (파이프 기호 | 사용) | |아이디 : ${id}, 이름 : ${name}| |
| [if문]?[then문] | if-then (단순 조건) | <p th:text=”${age < 20} ? ‘청소년’”></p> |
| [if문]?[then문]:[else문] | if-then-else (삼항 연산자처럼 사용) | <p th:text="${age < 20} ? '청소년' : '성인'"></p> |
| <… th:with=”변수명=${값}”> | 변수 선언 | <div th:with=”tValue=${’hello’}”> <h3 th:text="${tValue}"></h3> </div> |
📌 References
https://yeonyeon.tistory.com/153
https://itconquest.tistory.com/entry/Spring-Boot-Thymeleaf-개념-이해하기-사용방법
728x90