SpringBoot

타임리프 (Thymeleaf)

똑똑한망치 2024. 3. 15. 16:52
728x90
반응형

일반적으로 많이 사용하는 방식인 템플릿(template) 방식이 있다.

템플릿은 자바 코드를 삽입할 수 있는 HTML 형식의 파일이다.

 

스프링 부트에서는 템플릿 엔진을 지원한다. 템플릿 엔진에는 Thymeleaf, Mustache, Groovy, Freemarker, Velocity 등이 있다.

 

1. 타임 리프 사용하기

(1)  build.gradle 파일 작성

dependencies {
	(... 생략 ...)
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
}

(... 생략 ...)

 

 

(2)  "scr/main/resources/templates" 파일에 html 파일 작성

(3) controller 에서 "(html 파일 이름)" 으로 리턴하기

이때, 컨트롤러 어노테이션이 @Controller 로 해야한다.

@RestController 는 Json 형식으로 자동변환 하기 때문에 html 파일을 읽어 오지 못한다.

 

 

2. 데이터를 템플릿에 전달하기

// 예시 코드

import java.util.List;

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

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Controller
public class QuestionController {

    private final QuestionRepository questionRepository;

    @GetMapping("/question/list")
    public String list(Model model) {
        List<Question> questionList = this.questionRepository.findAll();
        model.addAttribute("questionList", questionList);
        return "question_list";
    }
}

 

이 예시에서 findAll() 을 통해 생성된 questionList 에 question 목록 데이터를 저장한다. 

addAttribute를 통해 Model 객체에 'questionList'라는 목록 데이터를 저장했다.

이때 Model 객체는 자바 클래스(Java Class)와 템플릿(template) 간의 연결 고리 역할을 한다.

Model 객체에 값을 담아 두면 템플릿에서 그 값을 사용할 수 있다.

Model 객체는 따로 생성할 필요 없이 컨트롤러의 메서드에 매개변수로 저장하기만 하면 스프링 부트가 자동으로 Model 객체를 생성한다.

 

 

3. 데이터를 화면에 출력하기

[파일명 : /resources/templates/question_list.html]

<table>
    <thead>
        <tr>
            <th>제목</th>
            <th>작성일시</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="question : ${questionList}">
            <td th:text="${question.subject}"></td>
            <td th:text="${question.createDate}"></td>
        </tr>
    </tbody>
</table>

 

예시 파일에서 사용한 타임리프 속성들 알아보기.

<tr th:each="question : ${questionList}">

QuestionController에서 list 메서드에서 조회한 질문 목록 데잍를 'questionList'라는 이름으로 Model 객체에 저장했다.

타임리프는 Model 객체에 저장한 questionList를 ${questionList}로 읽을 수 있다.

이 문장은 questionList에 저장된 데이터를 하나씩 꺼내 question 변수에 대입한 후 questionList의 개수만큼 반복하여 <tr> ... </tr> 문장을 출력하라는 의미이다.

 

<td th:text="${question.subject}"></td>

이 코드는 question 객체의 subject를 <td> 태그로 출력한다.

 

 

 

 

4. 자주 사용하는 타임리프(Timeleaf)의 3가지 속성

(1) 분기문 속성

if문, else if 문과 같은 분기문은 다음과 같이 사용한다.

th:if="${question != null}"

이 경우 question 객체가 null 이 아닌 경우에만 이 속성을 포함한 요소가 표시된다.

 

 

(2) 반복문 속성

th:each 반복문 속성은 자바의 for each 문과 유사하다.

th:each="question : ${questionList}"

 

반복문 속성은 다음과 같이 사용할 수도 있다.

th:each="question, loop : ${questionList}"

 

여기서 추가된 loop 객체를 이용하여 루프 내에서 다음과 같이 사용할 수 있다.

  • loop.index : 루프의 순서(루프의 반복 순서, 0부터 1씩 증가)
  • loop.count : 루프의 순서(루프의 반복 순서, 1부터 1씩 증가)
  • loop.size : 반복 객체의 요소 개수 (예를 들어 questionList 의 요소 개수)
  • loop.first : 루프의 첫 번째 순서인 경우 true
  • loop.last : 루프의 마지막 순서인 경우 true
  • loop.odd : 루프의 홀수 번째 순서인 경우 true
  • loop.even : 루프의 짝수 번째 순서인 경우 true
  • loop.current : 현재 대입된 객체

 

(3) 텍스트 속성

th:text=(속성) 은 해당 요소의 텍스트 값을 출력한다.

th:text="${question.subject}"


다른 표현 방식
<td>[[${question.subject}]]</td>
반응형