Thymleaf 소개
- Thymleaf(타임리프)는 HTML을 그대로 유지하면서도 변수 출력, 조건문, 반복문 등을 삽입할 수 있는 템플릿 엔진
//Java Code
public class Main {
public static void main(String[] args) {
String name = "재원";
String email = "sjww@example.com";
String html = String.format(
"<html><body>" +
"<p>이름: %s</p>" +
"<p>이메일: %s</p>" +
"</body></html>",name,email
);
System.out.println(html);
}
}
// Thymleaf 템플릿
import org.thymleaf.TemplateEngine:
import org.thymleaf.context.Context:
public class Main {
public static void main(String[] args) {
TemplateEngine engine = new TemplateEngine();
Context context = new Context();
context.serVariable("name","재원");
context.serVariable("email","sjww@example.com");
String template = ""
<html><body>
<p th:text="$(name)">이름</p>
<p th:text="$(email)">이메일</p>
</body></html>
"";
String result = engine.process(templat.context);
System.out.println(result);
}
}
- Thymleaf는 HTML과 자연스럽게 통합되는 템플릿 엔진으로 텍스트 출력, 조건 분기, 반복 처리, 속성 설정 등에 사용됨
| 기능 구분 | 문법 예시 | 설명 |
| 텍스트 출력 | th:text="${user.name}" | HTML 태그 안에 값 출력 (XSS방지) |
| 조건 분기 | th:if="${user != null}" | 조건에 따라 요소 렌더링 |
| 반복 처리 | th:each="item : ${items}" | 리스트 반복 출력 |
| 속성 설정 | th:href="@{/home}",th:classappend | HTML 속성에 동적 값 바인딩 |
| 조각 포함 | th:replace="fragment :: part" | 공통 영역 분리 및 재사용 |
| 폼 입력 | th:field="*{name}" | input,textarea,select에 모델 바인딩 |
| 메시지 | #{welcome.message} | 다국어 메시지 처리 (message.properties) |
'JAVA' 카테고리의 다른 글
| JAVA 객체지향 개념 정리 (1) | 2025.09.16 |
|---|---|
| JAVA 문법 규칙 및 GitHub 커밋 컨벤션 학습 (0) | 2025.09.15 |
| JSP/Servlet 기초 (1) | 2025.09.05 |
| Java 문법 기초 (1) | 2025.09.05 |
| Java란 무엇인가? (9) | 2025.08.14 |