카테고리 없음

스프링부트3 - 타임리프(thymeleaf)

아디봉 2024. 2. 5. 17:06

타임리프 

템플릿 엔진이며, 템플릿 엔진은 스프링 서버에서 데이터를 받아 우리가 보는 웹페이지. html 상에 그 데이터를 넣어 보여주는 도구 입니다. 

템플릿 엔진은 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}"

 

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 person = new Person();
        person.setId(1L);
        person.setName("홍길동");
        person.setAge(30);
        person.setHobbies(List.of("운동", "독서"));

        model.addAttribute("person", person);
        model.addAttribute("today", LocalDate.now());

        return "example";
    }

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

}

 

<!DOCTYPE html>
<html xmlns:th="http://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}"><!-- 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>