반응형

🧩 역할
스프링에서 가장 많이 쓰이는 서버 사이드 템플릿 엔진
🚀 특징
- HTML을 그대로 유지하면서, 서버 데이터를 동적 바인딩할 수 있음
- HTML 친화적이여서, 디자이너 / 프론트엔드와 협업하기 좋음
🔨 동작 구조
브라우저 요청
↓
Controller
↓ (Model에 데이터 담기)
Thymeleaf
↓
HTML 렌더링
↓
브라우저 응답
🔍 사용법
0️⃣ 설치
implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
implementation("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect")
1️⃣ 데이터 넣기
Model을 이용하여, template에 데이터를 key와 value 형태로 저장해서 넘겨줄 수 있음
@Controller
class QuestionController(
private val repository: QuestionRepository
) {
@GetMapping("/question/list")
fun list(model: Model): String {
val questionList: List<Question> = this.repository.findAll()
model.addAttribute("questionList", questionList)
return "question_list"
}
}
2️⃣ 데이터 표시하기
th: 형태로, 데이터를 바인딩할 수 있다.
<tr th:each="question : ${questionList}">
<td th:text="${question.subject}"></td>
<td th:text="${question.createDate}"></td>
</tr>
3️⃣유용한 문법
| th:text | 텍스트를 표현할 때 사용 | th:text=$[person.name} |
| th:each | 컬렉션을 반복할 때 사용 | th:each="person:${persons}" |
| th:if | 조건이 true일 때만 표시 | th:if="${person.age}>=20" |
| th:unless | 조건이 false일 때만 표시 | th:unless="${person.age}>=20" |
| th:href | 이동 경로 | th:href="@{/persons{id=${person.id}}}" |
| th:with | 변수값으로 지정 | th:with="name=${person.name}" |
| th:object | 선택한 객체로 지정 | th:object="${person}" |
4️⃣고급 문법
1. th: each loop
th: each= "question, loop : ${questionList}"
- loop.index : 루프의 순서 (0부터 1씩 증가)
- loop.count : 루프의 순서 (1부터 1씩 증가)
- loop.size : 루프의 개수
- loop.first : 루프의 첫 번째 순서인 경우 true
- loop.last : 루프의 마지막 순서인 경우 true
- loop.odd : 루프의 홀수 번째 순서인 경우 true
- loop.event : 루프의 짝수 번째 순서인 경우 true
- loop.current : 현재 대입된 객체
추후 추가 예정..
출처
https://docs.spring.io/spring-framework/reference/web/webmvc-view/mvc-thymeleaf.html
Thymeleaf :: Spring Framework
Thymeleaf is a modern server-side Java template engine that emphasizes natural HTML templates that can be previewed in a browser by double-clicking, which is very helpful for independent work on UI templates (for example, by a designer) without the need fo
docs.spring.io
반응형