Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

thymeleaf 본문

Spring/Spring Boot

thymeleaf

빌드이너프 2023. 12. 22. 12:19

타임리프 thymeleaf

템플릿 엔진

스프링 서버에서 데이터를 받아 HTML 상에 그 데이터를 넣어 보여주는 도구

 

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

h1 태그에는 ${이름}이 text 어트리뷰트로 할당되어 있다

p 태그에는 ${나이}가 text 어트리뷰트로 할당되어 있다

 

타임리프 표현식

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

 

뷰 작성

<!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>