JaPark Bug World
[SpringBoot] 타임리프 본문
7.1 사전지식 : 타임리프
타임리프는 템플릿 엔진이다. 템플릿 엔진은 스프링 서버에서 데이터를 받아 우리가 보는 웹 페이지, 즉 HTML 상에 그 데이터를 넣어 보여주는 도구이다. 다만 HTML과 함께 템플릿 엔진을 위한 문법을 살짝 섞어서 사용해야 한다.
템플릿 엔진 개념 잡기
// 간단한 탬플릿 문법을 위한 예
<h1 text=${이름}>
<p text=${나이}>
// 서버에서 보내준 데이터 예
{
이름: "홍길동"
나이: 11
}
값이 달라지면 그때 그때 화면에 반영하니 동적인 웹 페이지를 만들 수 있게 된다. 템플릿 엔진은 각각 문법이 미묘하게 달라서 템플릿 엔진마다 문법을 새로 배워야 한다. 대부분 구조는 비슷하며, 스프링은 타임리프를 권장하고 있다.
타임리프 표현식과 문법
표현식 | 설명 |
${...} | 변수의 값 표현식 |
#{...} | 속성 파일 값 표현식 |
@{...} | URL 표현식 |
*{...} | 선택한 변수의 표현식. th:object에서 선택한 객체에 접근 |
타임리프 문법
표현식 | 설명 | 예제 |
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} |
타임리프 사용을 위한 의존성 추가하기
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}
타임리프 문법 익히기용 컨트롤러 작성하기
@Controller
public class ExampleController {
@GetMapping("/thymeleaf/example")
public String thymeleafExample(Model model) {
Person examplePerson = new Person();
examplePerson.setId(1L);
examplePerson.setName("홍길동");
examplePerson.setAge(11);
examplePerson.setHobbies(List.of("운동", "독서"));
model.addAttribute("person", examplePerson);
model.addAttribute("today", LocalDate.now());
return "example";
}
@Setter
@Getter
class Person {
private Long id;
private String name;
private int age;
private List<String> hobbies;
}
}
/thymeleaf/example GET 요청이 오면 특정 데이터를 뷰, 즉 HTML로 넘겨주는 모델 객체에 추가하는 컨트롤러 메서드
뷰 작성하기
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>타임리프 익히기</h1>
<p th:text="${#temporals.format(today, 'yyyy-MM-dd')}"></p>
<div th:object="${person}">
<p th:text="|이름 : *{name}|"></p>
<p th:text="|나이 : *{age}|"></p>
<p>취미</p>
<ul th:each="hobby : *{hobbies}">
<li th:text="${hobby}"></li>
<span th:if="${hobby == '운동'}">(대표 취미)</span>
</ul>
</div>
<a th:href="@{/api/articles/{id}(id=${person.id})}">글 보기</a>
</body>
</html>
스프링부트3 백엔드 개발자 되기: 자바 편 책(저자 신선영)을 참고하여 정리한 내용입니다.
'개발새발 > 스프링부트3 백엔드 개발자 되기' 카테고리의 다른 글
[SpringBoot] OAuth2 (0) | 2024.04.29 |
---|---|
[SpringBoot]스프링 시큐리티 (0) | 2024.04.25 |
[SpringBoot] API와 REST API (0) | 2024.04.11 |
[SpringBoot] 스프링데이터 JPA에서 제공하는 메서드 사용해보기 (0) | 2024.04.11 |
[SpringBoot] 데이터베이스 조작이 편해지는 ORM (0) | 2024.04.08 |