# Thymeleaf란
Thymeleaf는 Spring Boot에서 가장 많이 사용되는 템플릿 엔진이며 HTML을 훼손하지 않고 사용할 수 있도록 설계된 엔진이다.
Natural Templates를 지원하여 순수 HTML 파일을 그대로 브라우저에서 열어볼 수 있다는 점이 특징이다. 또한 서버 사이드 렌더링(SSR) 방식으로 동작하며 학습 난도가 낮고 Spring 공식 템플릿 엔진으로 채택되어 있다.
# Thymeleaf 기본 표현식
Thymeleaf는 HTML 태그의 속성에 기능을 부여하는 방식으로 동작한다.
콘텐츠 영역에 값을 직접 출력하고 싶으면 [[...]]를 사용한다.
💡주요 표현식
👉변수 표현식: ${...}
👉선택자: *{...}
👉링크(URL): @{...}
💡리터럴 표현
👉텍스트: 'hello'
👉숫자: 13불린: true, false
👉null: null
💡문자열 연산
👉문자열 합치기: +
👉템플릿 문자: |hello ${name}|
💡산술 연산, 비교, 조건
👉산술: + - * /
👉비교: >, <, >=, ==
👉조건: if, switch, 삼항식 가능
# text vs utext
th: text는 HTML 태그를 escape 처리하여 문자열로 출력한다.
th: utext는 escape 하지 않으므로 HTML 태그가 그대로 렌더링 된다.
@GetMapping("/text-basic")
public String textBasic(Model model) {
model.addAttribute("data", "Hello <b>Spring</b>");
return "/basic/text-basic";
}
HTML 예시
<li>th:text=<span th:text="${data}"></span></li>
<li>th:utext=<span th:utext="${data}"></span></li>
<span>[[${data}]]</span>
# 변수(Variable) 사용 – Spring EL
Thymeleaf는 Spring EL을 사용해 다양한 데이터를 표현한다.
💡단순 변수
${data}
💡객체 접근
${user.username}
💡List 접근
${users [0]. username}
💡Map 접근
${userMap ['userA']. username}
💡지역 변수 선언
th:with 사용
<div th:with="item=${list[0]}"> <span th:text="${item.username}"></span> </div>
💡Controller 예시
@GetMapping("/variable") public String variable(Model model){ var userA = UserDto.builder().age(10).username("david").build(); var userB = UserDto.builder().age(19).username("kevin").build(); List<UserDto> list = Arrays.asList(userA, userB); Map<String, UserDto> map = new HashMap<>(); map.put("userA", userA); map.put("userB", userB); model.addAttribute("user", userA); model.addAttribute("users", list); model.addAttribute("userMap", map); return "/basic/variable"; }
# Spring 기본 객체 사용
자주 사용하는 객체인 session, bean을 Thymeleaf에서 직접 접근할 수 있다.
Controller
@GetMapping("/basic-obj")
public String basicObj(HttpSession session) {
session.setAttribute("sessionData", "Hello Session!");
return "/basic/session-obj";
}
HTML
<span th:text="${session.sessionData}"></span>
<span th:text="${@hello.hello('Spring!')}"></span>
# 날짜 처리 – #temporals
등록 날짜, 게시 날짜 등 날짜 정보는 #temporals 기능으로 쉽게 포맷팅 할 수 있다.
Controller
@GetMapping("/date")
public String date(Model model) {
model.addAttribute("localDateTime", LocalDateTime.now());
return "/basic/date";
}
HTML
<li th:text="${#temporals.format(localDateTime, 'yyyy-MM-dd HH:mm:ss')}"></li>
<li th:text="${#temporals.day(localDateTime)}"></li>
<li th:text="${#temporals.monthName(localDateTime)}"></li>
# URL 링크 처리
Thymeleaf는 URL 작성 방식을 단순화한다.
💡기본 URL
@{/hello}
💡Query Parameter
@{/hello(param1=${param1}, param2=${param2})}
💡Path Variable
@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}
Controller
@GetMapping("/link") public String link(Model model) { model.addAttribute("param1", "data1"); model.addAttribute("param2", "data2"); return "/basic/link"; }
# 리터럴(Literal)
리터럴은 문자열과 값 그대로를 출력할 때 사용한다.
<span th:text="'hello world'"></span>
<span th:text="'hello' + 'world'"></span>
<span th:text="|hello ${data}|"></span>
# 연산
💡산술 연산
<span th:text="10 + 2"></span>
💡비교 연산
<span th:text="10 > 2"></span>
💡조건식
<span th:text="(10 % 2 == 0)? '짝수' : '홀수'"></span>
💡Elvis 표현식
<span th:text="${data} ?: 'no data'"></span>
'spring' 카테고리의 다른 글
| Entity (0) | 2025.12.01 |
|---|---|
| JPA(=Java Persistance API) (0) | 2025.12.01 |
| Validation (0) | 2025.12.01 |
| AOP (Aspect Oriented Programming) (0) | 2025.12.01 |
| Spring boot 기초 (0) | 2025.11.28 |
