본문 바로가기

Spring boot

Thymeleaf(타임리프)

728x90
반응형

가공한 데이터를 이용하여 화면을 만드는 방법.

화면을 동적으로 만들려면 템플릿 엔진을 사용해야 한다.

미리 정의된 템플릿(Template)을 만들고 동적으로 HTML 페이지를 만들어서 클라이언트에 전달하는 방식.

요청이 올 때마다 서버에서 새로운 HTML 페이지를 만들어 주기 때문에 '서버 사이드 렌더링 방식' 이라고 한다.

 

서버 사이드 템플릿 엔진으로는 Thymeleaf, JSP, Freemarker, Groovy, Mustache 등이 있다.

스프링에서 권장하는 Thymeleaf의 큰 장점은 'natural templates' 다.

JSP의 확장자는 .JSP 서버 사이드 렌더링을 하지 않으면 정상적으로 화면 출력 결과를 볼 수 없다.

Thymeleaf 문법을 포함하고 있는 html 파일을 서버 사이드 렌더링을 하지 않고 브라우저에 띄워도 정상적인 화면을 볼 수 있다.

//웹 브라우저에서 Thymeleaf 파일 열어보기
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
	<meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
	<p th:text="${data}">Hello Thymeleaf!!</p>
</body>
</html>

th:text="${data}"라는 Thymeleaf 문법이 들어갔지만 html 파일이 깨지지 않고 정상적으로 출력 된다.

 

//애플리케이션을 실행시킨 후 서버 사이드 렌더링을 통해 해당 페이지에 접근하기

@Controller
@RequestMapping(value="/thymeleaf")
public class ThymeleafExController {
	
    @GetMapping(value="/ex01")
    public String thymeleafExample01(Model model) {
    	model.addAttribute("data", "타임리프 예제 입니다");
        return "thymeleafEx/thymeleafEx01";
    }
}

모델을 반환하면 화면에는 "타임리프 예제 입니다"라는 문구가 출력된다.

이게 바로 Thymeleaf가 지향하는 'natural templates'이다.

디자이너 또는 퍼블리셔는 자신이 작업한 내용을 html 파일로 바로 열어서 확인할 수 있으며

개발자는 파일을 받아서 html 태그 안에 Thymeleaf 문법을 추가하는 것만으로 동적으로 html 파일을 생성할 수 있다.

 


th:text 예제

//Dto

private String itemNm;

//html

<div>
	상품명 : <span th:text="${itemDto.itemNm}"></span>
</div>

 

th:each 예제(반복문)

//Controller

List<ItemDto> itemDtoList = new ArrayList<>();
for(int i=1; i<=10; i++) {
	ItemDto itemDto = new ItemDto();
    itemDto.setItemDetail("설명" + i);
    .....
    itemDtoList.add(itemDto);
}

//html

<tr th:each="itemDto, status: ${itemDtoList}">
	<td th:text="${status.index}"></td>
    <td th:text="${itemDto.itemNm}"></td>
	.....
</tr>

 

th:if   /   th:unless(조건문)

//html

<tr th:each="itemDto, status: ${itemDtoList}">
	<td th:if="${status.even}" th:text="짝수"></td>
    <td th:unless="${status.even}" th:text="홀수"></td>
    .......
//인덱스가 짝수일 경우 status.even은 true가 되므로 짝수 출력
//인덱스가 짝수가 아닐 경우, 홀수 일 경우 순번에서 홀수를 출력

 

th:switch  /  th:case 예제

//html

<tr th:each="itemDto, status: ${itemDtoList}">
	<td th:switch="${status.even}">
		<span th:case=true>짝수</span>
		<span th:case=false>홀수</span>

//${status.even}의 값이 true일 경우 짝수, false일 경우 홀수 출력

 

th:href 예제

//html

<a th:href="@{/thymeleaf/ex01}">ex01 페이지로 이동</a>

<a th:href="@{https://www.thymeleaf.org/}">타임리프 공식 홈페이지 이동</a>

 

Thymeleaf를 잘 활용한다면 협업하는 과정에서 생산성을 향상시킬 수 있을 것.

시작을 JSP로 했기 때문에? 비슷해서? 낯이 익었고 금방 이해할 수 있었다!

728x90
반응형

'Spring boot' 카테고리의 다른 글

회원 가입 기능 구현하기  (0) 2023.09.12
스프링 시큐리티(Spring Security)  (0) 2023.09.06
Spring DATA JPA  (2) 2023.09.02
쿼리 메소드  (0) 2023.09.02
@Entity 와 @Repository 설계  (0) 2023.09.01