[Thymeleaf] 타임리프 한 페이지로 정리해보기
[참고문헌 : 스프링부트3 백엔드 개발자 되기 저자: 신선영]
타임리프는 템플릿 엔진이다. 템플린 엔진이라 함은 웹페이지다. HTML 문법과 엔진을 위한 문법을 섞어야 한다.
타임리프 표현식을 보자
표현식 | 설명 |
${...} | 변수의 값 표현식 |
#{...} | 속성 파일 값 표현식 |
@{...} | URL 표현식 |
*{...} | 선택한 변수 표현식, th:object 에서 선택한 객체에 접근 |
타임리프 문법을 보자
표현식 | 설명 | 예제 |
th:text | 텍스트를 표현할 때 사용 | th:text=${person.name} |
th:each | 컬렉션을 반복할 때 사용 | th:each="person:${person}" |
th:if | 조건이 True 일 때만 표시 | th:if="${person.age}>=20" |
th:unless | 조건이 false 인 때만 표시 | if:unless="${person.age} >= 20" |
th:href | 이동 경로 | th:href="@{/person(id=${person.id})}" |
th:with | 변숫값으로 지정 | th:with="name=${person.name}" |
th:object | 선택한 객체로 지정 | th:object="${person}" |
타임리프 사용을 위해서 의존성을 추가해야 합니다
implementaion 'org.springframework.boot:spring-boot-starter-thymleaf'
스프링 서버에서 뷰로 보내볼까요? 여기서는 GET 요청방식으로, 템플릿 엔진은 타임리프를 사용해보겠습니다.
어떻게 데이터가 이동하는 지 잘 확인하시면 됩니다.
@Controller
public class ExampleController {
@GetMapping("/thymeleaf/example")
public String thymleafExample(Model model) {
Person examplePerson = new Person();
examplePerson.setId(1L);
examplePerson.setName("홍길동");
model.addAttribute("person", examplePerson);
return "example"
}
이렇게 컨트롤러를 작성했다고 칩시다. 실무에서는 실제로 이러한 방식으로 데이터를 전달합니다.
Model 은 뷰로 데이터를 넘겨줍니다. 그래서 model.addAttribute("person", examplePerson) 여기를 보면
HTML 에 person 이라는 키에 exaplePerson 객체를 넣어 보내주겠다는 것이고
return "example" 은 이 HTML 파일명이 example 이라는 것이고 여기 파일에다가 넘기라 이 말입니다.
그럼 이 컨트롤러의 요청을 전달받은 뷰를 살펴보겠습니다.
<-선언 생략->
<div th:object=${person}>
<p text="이름: *{name}"> </p>
</div>
<a th:href="@{/api/articles/{id}(id=${person.id})}">글 보기 </a>
짜잔! 정말 정말 간단하게 작성을 해보았습니다.
타임리프 문법에 맞게 받은 데이터를 출력하는 코드입니다.
*{name} 은 ${person} 에서의 name 데이터를 의미하는 거겠죠!
그러면 잘 뜰겁니다 ㅎㅎ
간단간단합니다 어렵지 않아욥
- 끝 -
더 자세한 정보는 링크 첨부하고 갑니다 ㅎㅎ
https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html
Getting started with the Standard dialects in 5 minutes - Thymeleaf
Getting started with the Standard dialects in 5 minutes This guide will take you through some of the most important concepts you need to know to understand a Thymeleaf template written in the Standard or SpringStandard dialects. It is not a substitute for
www.thymeleaf.org