[Thymeleaf] 타임리프 개념 및 사용법
타임리프(Thymeleaf)란?
💡 템플릿 엔진의 일종으로,
html 태그에 속성을 추가해 페이지에 동적으로 값을 처리할 수 있다.
백엔드 서버에서 동적으로 렌더링 하는 용도로 사용된다.
순수 html을 그대로 유지하면서 view template도 사용할 수 있는 타임리프의 특징을
네츄럴 템플릿 (natural templates) 이라 한다.
🛜 공식 사이트 주소 : https://www.thymeleaf.org/
Thymeleaf
Integrations galore Eclipse, IntelliJ IDEA, Spring, Play, even the up-and-coming Model-View-Controller API for Java EE 8. Write Thymeleaf in your favourite tools, using your favourite web-development framework. Check out our Ecosystem to see more integrati
www.thymeleaf.org
사용법
➡️ 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>
타임리프를 사용할 html 파일 상단에 하단 태그를 추가한다.
<html xmlns:th="http://www.thymeleaf.org">
⬇️ 하단 예제를 통해서 적용법을 알아보려한다.
HelloController.java
@Controller
public class HelloController {
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "hello!!!");
/**스프링 부트 thymeleaf viewName 매핑
resources:templates/ +{ViewName}+ .html*/
return "hello";
}
}
resources/templates/hello.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>
위 라이브러리를 추가하게되면, application.yml 혹은 properties에 하단 코드가 자동으로 세팅된다.
기본 설정을 원하지 않는다면 직접 수정해도 된다.
➡️ application.yml
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
➡️ application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
기본 표현식
⬇️ 하단 표를 통해 기본 표현식에 대해서 알아보려고 한다.
ex: th:text="${변수명}"
표현 | 설명 | 예제 |
@{...} | URL 링크 표현식 | th:href="${/css/bootstrap.min.css}" th:href="@{/{itemId/edit(itemId=${item.id})}" |
| ... | | 리터럴 대체 | th:text="|Hi ${user.name}!|" (= th:text="'Hi '+${user.name}+'!'" |
${...} | 변수 | th:text=${user.name} |
th:each | 반복 출력 | <tr th:each="item: ${items}"> <td th:text="${item.price}">100</td> </tr> |
*{...} | 선택 변수 | <tr th:object="${items}"> <td th:text="*{price}">100</td> </tr> |
#{...} | properties같은 외부 자원 | th:text="#{member.register}" |
OUTRO
오늘은 타임리프 사용법에 대해서 간단하게 알아봤습니다.
추후 포스팅에서는 심화된 다양한 문법에 대해서도 다룰 예정입니다.
그러면 다음 포스팅에서 뵙겠습니다.
참고
🛜 타임리프 문법 : https://yeonyeon.tistory.com/153
[Thymeleaf] 타임리프란? (+기본적인 사용법)
간단한 CRUD를 구현하다가 org.thymeleaf.exceptions.TemplateProcessingException 에러를 너무 많이 겪어서 타임리프에 대해 잠깐 공부하기로 했다. (위 에러는 타임리프 문법을 잘못 쓰는 등의 이유로 특정 url
yeonyeon.tistory.com