Programming/Spring

[Spring Boot] Thymeleaf란? (개념 / 특징 / 사용법)

JeongKyun 2022. 3. 28.
반응형

서론

이번글에서는 템플릿을 이용하여 보다 쉽게 화면을 구현할 수 있는 기술이라 하는 Thymeleaf에 대해서 알아보자.

 


 

Thymeleaf의 특징 | 강점 

HTML5 웹 표준을 준수하는 템플릿이다.

  • 전체적인 문법이 html5 마크업 표준을 최대한 해치지않게 설계되어있다.
  • 템플릿 문법을 아예 템플릿에서 분리하여 사용할 수 있다. (Decoupled Logic)

--> 템플릿 엔진이 작동하지 않아도 렌더링되는 정적 목업 페이지

--> 디자이너가 이해하기 쉬운 코드를 제공한다.

 


 

템플릿 문법 적용 방법 3가지

1. "th:" tag

2. "data-th-" attribute

3. decoupled logic

 


 

표현 방식(Expressions)

Variable Expressions :    ${...}

Selection Expressions :   *{...}

Message Expressions :   #{...}

Link URL Expressions :   @{...}

Fragment Expressions:   ~{...}

 


자주 사용하는 문법

th

th:text
<span th:text="${member}"></span>

화면에 값을 출력할 때 사용한다.

 

 

 

th:if
<div th:if="${error}">
    <p>에러가 발생했습니다.</p>
</div>

조건문처럼 사용할 수 있고, 조건이 성립될 때만 보여진다.

 

 

 

th:errors
<ul>
   <li th:errors="*{id}" />
   <li th:errors="*{name}" />   
</ul>

해당 value의 값에 error가 발생할 경우 출력한다.

 


 

form
th:action
<form th:action="@{/login}"></form>

form 태그 사용 시, 해당 경로로 요청을 보낼 때 사용한다.

 

 

 

th:object
<form th:action="@{/login}" th:object = "${member}"></form>

form submit을 할 때 form의 데이터가 th:object에 설정해준 객체로 받아지게한다.

 

 

 

th:field
<form th:action="@{/login}" th:object = "${member}">
	<input type="text" th:field="*{name}" />
</form>

각 필드들을 매핑해주는 역할을 하며, th:object에 설정해 준 객체의 내부와 매칭해주는 역할을 한다.

댓글

💲 많이 본 글