What I Learned/Framework
[Spring Boot] 템플릿 엔진 Thymeleaf 기초
Interrobang
2023. 7. 31. 21:45
특징
natural template
스프링과 함께 사용하기에 최적화 되어 있음
세팅
Gradle dependency 추가
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
사용할 HTML 파일 html 태그에 XML namespace를 명시
<html xmlns:th="http://www.thymeleaf.org">
controller에서 parameter 전달
- model 객체 선언 후 addAttribute() 활용
@GetMapping("example")
public String example(Model model) {
String name = "joon ki";
model.addAttribute("name", name);
return "example";
}
기본 문법
데이터 바인딩: th:text 활용
<div th:text="${text}"></div>
조건문: th:if / th:unless 활용
<div th:if="${num > 10}">True 입니다.</div>
<div th:unless="${num > 10}">False 입니다.</div>
th:each 활용
<table>
<tr th:each="user : ${userList}">
<td th:text="|id: ${user.id}, name: ${user.name}, age: ${user.age}|"></td>
<td th:text="|usertype: ${student.usertype}|"></td>
</tr>
</table>
기타 유용한 문법
th:href
th:with
th:value
th:fragment
th:replace
th:block
th:insert
script 태그 안에서 Thymeleaf 문법을 사용하고자 할 때 필수
<script th:inline="javascript">
~~
</script>