반응형

들어가며

Thymeleaf

  • 스프링 부트에서 자동 설정으로 지원하는 서버 사이드 자바 템플릿 엔진의 한 종류이다.
  • 스프링 프레임워크의 MVC 구조에서 View를 담당하는 라이브러리이다.
  • JSP와 달리 Servlet Code로 변환되지 않는다.
  • 페이지 수정시 서버를 실행하지 않고도 수정이 가능하다.

JSP를 권장하지 않는 이유

  • JSP를 사용하면 JAR 패키징을 할 수 없어 WAR 패키징을 해야 한다.
  • JAR는 JRE로만 실행 가능하고, WAR는 실행을 위해 WAS가 필요하다.
  • Undertow라는 서블릿 엔진이 JSP를 지원하지 않는다.
  • JSP 의존성이 문제가 생기는 경우가 있다.

기본 예제

Dependencies

dependencies {
    ...
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'    
}

application.properties

# thymeleaf 코드 수정 후 Build Project만 수행해주면 서버 재시작 없이 브라우저에서 수정사항 확인 가능
spring.thymeleaf.cache=false

example.html

  • 경로 : ~/src/main/resources/templates/example.html
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<h2>Hello</h2>
</body>
</html>

서버 실행 및 확인

th:text

설명

  • 일반 텍스트를 노출하는 속성

ExampleController

@Controller
public class ExampleController {
    @GetMapping("/example")
    public String example(Model model) {
        model.addAttribute("name", "john");
        return "example";
    }
}

example.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<div>username : <span th:text="${name}"></span></div>
<div th:text="${'Hi, ' + name}"></div>
<div th:text="|Hi, ${name}|"></div>
<div th:text="'Hi, ' + ${name}"></div>
<div th:text="${name == 'john'}"></div>
<div th:text="${name == 'john' ? 'ok' : 'no'}"></div>
</body>
</html>

th:value

설명

  • 태그의 value를 설정하는 속성

ExampleController

@Controller
public class ExampleController {
    @GetMapping("/example")
    public String example(Model model) {
        model.addAttribute("name", "john");
        return "example";
    }
}

example.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<input type="text" th:value="${name}">
</body>
</html>

th:utext

설명

  • html을 노출하는 속성

ExampleController

@Controller
public class ExampleController {
    @GetMapping("/example")
    public String example(Model model) {
        model.addAttribute("html", "<h1>Hello World</h1>");
        return "example";
    }
}

example.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<div th:utext="${html}"></div>
</body>
</html>

th:each

설명

  • 리스트 항목을 하나씩 노출하는 속성

ExampleController

@Controller
public class ExampleController {
    @GetMapping("/example")
    public String example(Model model) {
        List<User> users = List.of(
            new User("john", 25),
            new User("tom", 30),
            new User("jane", 45)
        );
        model.addAttribute("users", users);
        return "example";
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    private static class User {
        private String name;
        private int age;
    }
}

example.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<table>
    <thead>
    <tr>
        <th>index</th>
        <th>name</th>
        <th>age</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="user, iter : ${users}">
        <td th:text="${iter.index}"></td>
        <td th:text="${user.name}"></td>
        <td th:text="${user.age}"></td>
    </tr>
    </tbody>
</table>
</body>
</html>

th:with

설명

  • 변수에 값을 담아 사용하는 속성

example.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<div th:with="name = 'john', age = 25">
    <span th:text="${name}"></span> : <span th:text="${age}"></span>
</div>
</body>
</html>

th:if, th:unless

설명

  • 조건에 해당되거나 해당되지 않을 경우에 노출하는 속성

ExampleController

@Controller
public class ExampleController {
    @GetMapping("/example")
    public String example(Model model) {
        model.addAttribute("type", "DEV");
        return "example";
    }
}

example.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<th:block th:if="${type == 'DEV'}">DEV</th:block>
<th:block th:unless="${type == 'DEV'}">PROD</th:block>
</body>
</html>

th:switch, th:case

설명

  • 조건에 해당되거나 해당되지 않을 경우에 노출하는 속성

ExampleController

@Controller
public class ExampleController {
    @GetMapping("/example")
    public String example(Model model) {
        model.addAttribute("type", "DEV");
        return "example";
    }
}

example.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<th:block th:switch="${type}">
    <th:block th:case="DEV">DEV</th:block>
    <th:block th:case="*">PROD</th:block>
</th:block>
</body>
</html>

th:src

설명

  • src를 설정하는 속성

이미지 파일 준비

  • 경로 : ~/src/main/resources/static/images/pet.jpg

example.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<img th:src="@{/images/pet.jpg}">
</body>
</html>

date

설명

  • 날짜 객체(Date, LocalDateTime)를 받아와 포맷팅하는 예제

ExampleController

@Controller
public class ExampleController {
    @GetMapping("/example")
    public String example(Model model) {
        model.addAttribute("date1", new Date());
        model.addAttribute("date2", LocalDateTime.now());
        return "example";
    }
}

example.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<div th:text="${#dates.format(date1, 'yyyy-MM-dd HH:mm:ss')}"></div>
<div th:text="${#temporals.format(date2, 'yyyy-MM-dd HH:mm:ss')}"></div>
</body>
</html>

javascript

설명

  • javascript의 값으로 전달한 값을 활용하는 예제

ExampleController

@Controller
public class ExampleController {
    @GetMapping("/example")
    public String example(Model model) {
        model.addAttribute("name", "john");
        return "example";
    }
}

example.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<script th:inline="javascript">
    const name1 = [[${name}]];
    const name2 = /*[[${name}]]*/ '서버에서 전달한 name값';
    alert(name1 + name2);
</script>
</body>
</html>

참고

반응형

'Development > Spring' 카테고리의 다른 글

[Spring] @Value  (0) 2021.08.02
[Spring] Sharding  (0) 2021.07.07
[Spring] Model Mapping  (0) 2021.06.13
[Spring] Spring Security  (0) 2021.05.29
[Spring] spring-retry  (0) 2021.05.27

+ Recent posts