타임리프(Thymeleaf) 알아보기

·2023년 12월 3일
0

Spring Boot

목록 보기
10/21
post-thumbnail

🍃 Thymeleaf란 무엇일까?

타임리프란 템플릿 엔진이다. 템플릿 엔진이란 스프링 서버에서 데이터를 받아 우리가 보는 웹 페이지, 즉 HTML 상에 그 데이터를 넣어 보여 주는 도구이다. 템플릿 엔진은 HTML과 함께 템플릿 엔진을 위한 문법을 살짝 섞어 사용해야 한다.

템플릿 엔진 제대로 알기

<h1 text=${이름}>
<p text=${나이}>

h1, p 태그에는 각각 ${이름}, ${나이}가 text 어트리뷰트로 할당되어 있다. 이것이 바로 템플릿 문법이다. 이렇게 작성하면 서버에서 이름, 나이라는 키로 데이터를 템플릿 엔진에 넘겨 주고, 템플릿 엔진은 이를 받아 HTML에 값을 저장한다.

값이 달라지면 그때 그때 화면에 반영하니 동적인 웹 페이즈를 만들 수 있게 되는 것이다.

타임리프 표현식

전달받은 데이터를 사용자들이 볼 수 있는 뷰로 만들기 위해 사용되는 표현식은 아래와 같다.

표현식설명
${..}변수의 값 표현식
#{..}속성 파일 값 표현식
@{..}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}"

예시로 살펴보기

1. 타임리프 사용을 위해 의존성 추가

build.gradle

(생략)
dependencies {
	(생략)
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' // 타임리프
}

2. 타임리프 문법 익히기용 컨트롤러 작성

ExampleController.java

package me.ansoohyeon.springbootdeveloper.controller;

import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDate;
import java.util.List;

@Controller // 컨트롤러라는 것을 명시적으로 표현
public class ExampleController {
    
    @GetMapping("/thymeleaf/example")
    public String thymeleafExample(Model model){ // 뷰로 데이터를 넘겨 주는 모델 객체
        Person examPerson = new Person();
        examPerson.setId(1L);
        examPerson.setName("홍길동");
        examPerson.setAge(11);
        examPerson.setHobbies(List.of("운동", "독서"));
        
        model.addAttribute("person", examPerson); // Person 객체 저장
        model.addAttribute("today", LocalDate.now());
        
        return "example"; // example.html라는 뷰 조회
    }

    @Getter
    @Setter
    class Person{
        private Long id;
        private String name;
        private int age;
        private List<String> hobbies;
    }
}

3. 뷰 작성

example.html

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>타임리프 익히기</h1>
    <!--  LocalDate를 yyyy-MM-dd 포맷으로 변경  -->
    <p th:text="${#temporals.format(today, 'yyyy-MM-dd')}"></p>
    <div th:object="${person}"> <!-- person을 선택한 객체로 지정 -->
        <p th:text="|{이름 : *{name}}"></p>
        <p th:text="|{나이 : *{age}}"></p>
        <p>취미</p>
        <ul th:each="hobby : *{hobbies}"> <!-- hobbies 개수만큼 반복 -->
            <li th:text="${hobby}"></li>
            <!-- 반복 대상이 운동이라면 '대표 취미'라는 표시 추가 -->
            <span th:if="${hobby == '운동'}">(대표 취미)</span>
        </ul>
    </div>

    <!-- 1번 블로그 글을 보러 이동 -->
    <a th:href="@{/api/articles/{id}/(id=${person.id})}">글 보기</a>
</body>
</html>

4. 뷰 테스트

지정해 준 URL로 접속하면 위와 같은 화면이 나타난다.

profile
풀스택 개발자 기록집 📁

0개의 댓글