타임리프(Thymeleaf)는 스프링 부트에서 공식적으로 지원하는 뷰 템플릿(view template)이다.
build.gradle
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
서버 사이드 렌더링
타임리프는 서버 사이드에서 HTML을 렌더링한다.
클라이언트에 보내기 전에 서버에서 템플릿을 처리하여 최종 HTML을 생성합니다. 이 방식은 Java 기반 웹 애플리케이션에서 동적인 콘텐츠를 생성하는 데 유용하며, 페이지의 일부를 동적으로 업데이트하거나 사용자 입력을 반영하는 등의 기능을 쉽게 구현할 수 있다.
자연스러운 템플릿(Natural Template)
내츄럴 템플릿은 템플릿 파일이 HTML 파일로서 유효하다는 의미이다.
타임리프 템플릿은 브라우저에서 직접 열어도 유효한 HTML로 표시되며, 개발자는 브라우저에서 직접 템플릿을 미리 볼 수 있다. 이 접근법은 템플릿 작성 및 유지보수를 쉽게 하고, 프론트엔드 개발자와 백엔드 개발자 간의 협업을 용이하게 한다.
사용 선언
<html xmlns:th="http://www.thymeleaf.org">
|...| - 리터럴 대체
th:text="|Welcome to our application, ${user.name}!|"
th:onclick="|location.href='@{/basic/items/add}'|"
리터럴을 사용하지 않으면, 문자와 표현식 등이 분리되어 있기 때문에 더해서 사용해야 한다.
문자와 표현식을 각각 따로 더해서 사용해야 하기 때문에 복잡해진다.
th:text="'Welcome to our application, ' + ${user.name} + '!'"
@{...} - URL 링크 표현식
href="value1" → th:htref="value2" 변경href 속성이 사용되고, 뷰 템플릿을 거치면 th:href의 값으로 대체되어 동적으로 변경할 수 있다.th:href="@{/css/bootstrap.min.css}"
th:href="@{|/basic/items/${item.id}|}"
th:href="@{/basic/items/{itemId}(itemId=${item.id})}"
th:href="@{/basic/items/{itemId}(itemId=${item.id}, query='test')}"
→ http://localhost:8080/basic/items/1?query=test
<link href="../css/bootstrap.min.css"
th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
${...} - 변수 표현식
item.getPrice()<td th:text="${item.price}">25000</td>
#{...} - 외부 자원 변수 표현식
<p th:text="#{welcome.message}"></p>
*{...}
<input type="text" th:value="*{name}" />
th:text - 내용 변경
<td th:text="${item.price}">25000</td>
th:each - 반복 출력
<tr th:each="item : ${items}">
th:onclick - 이동
onclick="location.href='registerForm.html'"
th:onclick="|location.href='@{/basic/items/add}'|"
<tr>...</tr> 태그를 포함해서 생성된다.