Thymeleaf 설정
스프링 프로젝트를 생성할 때, 우측 dependency에서 thymeleaf를 추가해준다.
프로젝트에서 직접 추가를 하는 경우, 라이브러리를 추가
Gradle
build.gradle
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
Maven
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
설정을 마쳤으면, thymeleaf를 사용할 html 파일 html 태그에 다음을 추가한다.
<html xmlns:th="http://thymeleaf.org">
Thymeleaf 기본 사용법
- URL 링크 표현식 - @{...}
<a th:href="@{/basic/link}">링크</a>
- '/basic/link' 을 연결해준다.
- 리터럴 대체 - |...|
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
- thymeleaf에서는 문자와 표현식 등은 분리되어 있기 때문에 구분한 다음 더해서 사용해야한다.
그러나 리터럴 대체 문법을 사용하면 구분 없이 한 문자열로 사용이 가능하다.
<span th:text="|Welcome to our application, ${user.name}!|">
- 반복 출력 - th:each
<tr th:each="item : ${items}">
- 모델에 items 으로 저장된 컬렉션 데이터를 item 이라는 변수로 하나씩 참조할 수 있다.
- 변수 표현식 - ${...}
<td th:text="${item.name}">apple</td>
- 모델에 저장된 값이나, 타임리프 변수로 선언한 값을 조회할 수 있다.