본문 바로가기

IT/Spring

[Spring Boot] thymeleaf 사용방법

1. Thymeleaf 란

Thymeleaf는 View Template Engine입니다. 그리고 컨트롤러에서 전달받은 데이터를 이용해 동적인 페이지를 만들 수 있습니다.
태그의 속성으로 thymeleaf 명령어를 사용할 수 있으며 html 파일 내에서 사용이 가능합니다. 

 

2. Thymeleaf 적용

spring boot 2.2.2.RELEASE 버전에서 테스트한 내용입니다.

thymeleaf의 default prefix는 src/main/resources/templates이며 suffix는 .html입니다.

1) dependency (pom.xml)

    <dependencies>
	...
    	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
	...
    </dependencies>        

2) Controller

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/")
public class HomeController {

    @GetMapping("/")
    public ModelAndView indexPage() {
    	//view name으로 page 파일 명을 입력한다.
        //prefix + 파일명 + suffix
        ModelAndView modelAndView = new ModelAndView("index");

        Map<String, Object> info = new HashMap<>();
        info.put("name", "kim");
        info.put("age", 29);

        List<String> datas = new ArrayList<>();
        datas.add("red");
        datas.add("orange");
        datas.add("yellow");

        modelAndView.addObject("info", info);
        modelAndView.addObject("datas", datas);

        return modelAndView;
    }
}

3) src/main/resources/templates/index.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Thymeleaf Test</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <th:block th:each="data:${datas}">
            <h1 th:text="${data}"></h1>
        </th:block>

        <span th:text="${info.name}"></span>
        <span th:text="${info.age}"></span>
    </body>
</html>
Controller에서 전달받은 datas와 info를 화면에 출력합니다.

 

4. thymeleaf 문법 정리

1) ${...} 표현식

${...} 표현식을 이용해 컨트롤러에서 전달받은 변수에 접근할 수 있으며 th:속성명 내에서만 사용할 수 있습니다.

 

2) @{...} 표현식

@{...} 표현식은 서버의 contextPath를 의미하며 @{/} 는 "/contextPath/" 를 의미합니다.

 

3) 문자 합치기

합치고 싶은 문자열을 "|" 으로 감싸거나 + 연산자를 이용해 문자를 합칠 수 있습니다.
<div th:text="|My name is ${info.name} !! |"></div>
<div th:text="'My name is '+ ${info.name} + ' !! '"></div>

 

4) 비교 연산자

<!-- 이항 연산자 -->
<div th:text="${info.name != 'kim'}"></div>
<div th:text="${info.age >= 30}"></div>

<!-- 삼항 연산자 -->
<div th:text="${info.name == 'kim' ? 'ok' : 'no'}"></div>

 

5) th:text

태그 내에 text를 수정합니다.
<div th:text="${info.name}"></div>
 <!--<div>kim</div>-->

 

6) th:value

태그 내에 value를 수정합니다.
<input type='text' th:value="${info.name}">

 

7) th:if, th:unless

if else 속성을 이용해 조건문을 표현합니다.
<th:block th:if="${info.age < 30}">당신은 30대가 아닙니다.</th:block>
<th:block th:unless="${info.age >= 30}">당신은 30대입니다.</th:block>

 

8) th:switch, th:case

switch문을 이용해 조건문을 표현합니다.
<th:block th:switch="${info.name}">
  <div th:case="lee"> 당신은 이씨 입니다.</div>
  <div th:case="kim"> 당신은 김씨 입니다.</div>
</th:block>

 

9) th:each

each문을 이용해 반복문을 표현합니다.
<th:block th:each="data:${datas}">
	<h1 th:text="${data}"></h1>
</th:block>

 

변수명 앞에 status 변수를 추가해 row에 대한 추가정보를 얻을 수 있습니다.
<th:block th:each="data,status:${datas}">
	<h1 th:text="|${status.count} ${data}|"></h1>
</th:block>    
status 속성

index :
0부터 시작
count : 1부터 시작
size : 총 개수
current : 현재 index의 변수
event/odd :
짝수/홀수 여부
first/last :
처음/마지막 여부