Spring Boot

Thymeleaf란?

git-sun 2023. 3. 13. 16:19

 

Thymeleaf란?

 

Thymeleaf란?

  • 자바 웹 어플리케이션에서 HTML, XML, JavaScript, CSS 등의 웹 리소스를 처리하는데에 사용되는 Server-side Template Engine입니다.
  • 동적인 View Template Engine이기도 합니다.
  • 사용자 인터페이스를 생성하는 데에 사용되고, 서버 측에서 렌더링되기 때문에 클라이언트 측에서 JavaScript를 사용하지 않아도 됩니다.

 

 

 

 

Thymeleaf의 장점?

  1. HTML 기반 : HTML을 기반으로 하기 때문에 HTML 파일을 보기 쉽게 유지할 수 있습니다. HTML에 Thymeleaf가 자연스레 녹아있는 모습입니다.
  2. 다양한 기능 : 변수, 반복문, 조건문, 속성, 링크 처리, 레이아웃, 폼 처리, 메시지 처리 등 다양한 기능을 제공합니다
  3. 쉬운 템플릿 작성 : Thymeleaf는 쉬운 로직을 가지고 있어 빠른 템플릿 작성이 가능합니다
  4. 높은 호환성 : 특히 Spring Framework에 최적화 되어있어 높은 호환성을 제공합니다
  5. 직관적인 문법 : HTML 안에서 직관적인 문법을 쓰기 때문에 의미를 파악하기 쉽습니다
  6. 높은 성능 : Thymeleaf는 렌더링할 때 자바 코드를 생성하므로 높은 성능을 보장합니다
  7. 템플릿 캐싱 : Thymeleaf는 템플릿 캐싱도 지원합니다. 따라서 빠른 응답 시간을 보장합니다

 

 

 

 

Thymeleaf의 단점?

  1. 높은 러닝 커브 : Thymeleaf는 직관적인 문법을 제공하는 게 장점이라고 했습니다만, 처음 사용할 때는 문법과 동작 방식을 이해하는데에 있어 러닝 커브가 높을 수 있습니다. 특히, 기존 JSP와 같은 다른 템플릿 엔진에 익숙하신 분들은 Thymeleaf가 생소하실 수 있습니다.
  2. 대규모 어플리케이션에서의 늦은 처리 속도 : Thymeleaf는 HTML 템플릿을 처리하기 위해서 자바 코드를 생성한다고 했습니다. 그런데 이런 점으로 인해서 큰 규모의 어플리케이션에서는 처리 속도가 느려질 수 있습니다. 이를 개선하기 위해 템플릿 캐싱과 같은 기능을 제공하지만, 이 기능을 사용하더라도 처리 속도가 느려질 수 있습니다.
  3. 구문 에러 디버깅 어려움 : Thymeleaf로 템플릿 작성 시에 구문 에러가 발생하면, 어디의 어떤 부분에서 에러가 발생했는지 찾기가 어려워 디버깅이 쉽지 않습니다. 따라서 코드 작성 시 주의해야하고, 구문 에러 발생 시를 대비하여 적절한 에러 처리를 해야합니다.
  4. 복잡한 로직 처리의 어려움 : Thymeleaf는 단순한 로직을 처리하는 데에는 직관적이기도 해서 매우 용이합니다. 그러나 복잡한 로직을 처리하는데에는 어려움이 있습니다. 이 경우, 서버 사이드에서 코드를 수정하거나 JavaScript의 코드를 수정하는 등 다른 기술을 사용해야하는 경우가 있을 수 있습니다.

 

 

 

 

Thymeleaf의 기능들

  1. 표현식(Expression) : 변수, 조건문, 반복문 등의 표현식들 사용 가능, 자바 객체와 쉽게 통합되어 작동
  2. 반복문 : 자바의 for, while문과 같은 형태의 반복문 사용 가능
  3. 조건문 : 자바의 if, switch문과 같은 형태의 조건문 사용 가능
  4. 속성(Attribute) : HTML의 다양한 요소의 속성을 Thymeleaf로 표현 가능
  5. 링크 URL 처리 : HTML 링크 요소의 href 속성을 URL 생성 및 클릭 시 이동 가능
  6. 레이아웃 Including : 여러 페이지에서 공통적으로 사용되는 레이아웃을 템플릿으로 작성하고, 이 템플릿을 다른 페이지에서 including하여 사용 가능
  7. 폼 처리 : HTML 폼 요소로부터 넘어온 데이터 처리 가능
  8. 메시지 처리 : 다국어 지원을 위해 메시지 파일을 사용할 수 있고, 해당 메시지 표시 가능

 

 

 

 

Thymeleaf의 표현식

Thymeleaf의 표현식 종류는 다음과 같습니다

  • 단순 표현식 
    • Variable Expressions : ${...}
    • Selection Variable Expressions : *{...}
    • Message Expressions : #{...}
    • Link URL Expressions : @{...}
    • Fragment Expressions : ~{...}

 

  • 리터럴
    • Text literals : 'one text', 'Another one!' ...
    • Number literals : 0, 34, 3.0...
    • Boolean literals : true, false
    • Null literal : null

 

  • Text Operations
    • String concatenation : +
    • Literal substitutions : |The name is ${name}|

 

  • Arithmetic Operations
    • Binary operators : +, -, *, /, %
    • Minus sign (unary operator) : -

 

  • Boolean operations
    • Binary operators : and, or
    • Boolean negation (unary operator) : !, not

 

  • Comparisons and equality
    • Comparators : >, <, >=, <=
    • Equlity operators : ==, !=

 

  • Conditional operators
    • if-then : (if..) ? (then..)
    • if-then-else : (if..) ? (then..) : (else..)
    • Default : (value..) ?: (default value..)

 

  • Special tokens
    • No-Operations : _

 

 

 

 

 

Thymeleaf 사용 예시

  • th:속성명으로 데이터 바인딩
  • ${변수명}으로 서버에서 전달받은 데이터를 표현
  • ${object.component}으로 객체의 요소 표현
  • ${object.method( )}로 객체의 메소드 호출
  • @{링크 주소}로 링크 표현
  • @{/...}절대 경로 표현
  • @{...}상대 경로 표현

 

1. 표현식

<!-- 객체의 속성(user.name)를 변수로 받아(${user.name}) 출력(th:text) -->
<div th:text="${user.name}"></div>

<!-- 객체의 속성(user.age)에 연산(user.age > 18)한 것을 변수로 받아(${...}) 조건문(th:if) -->
<p th:if="${user.age > 18}">성인</p>

<!-- 객체의 메소드(user.getName()) 호출 -->
<p th:text="${user.getName()}" />

 

 

2. 반복문

<!-- fruits라는 리스트 안의 요소를 th:each라는 반복문으로 출력(th:text) -->
<ul>
  <li th:each="fruit : ${fruits}" th:text="${fruit}"></li>
</ul>

 

 

3. 조건문

<!-- th:if 조건문 -->
<p th:if="${user.gender == 'male'}">남성</p>

<!-- th:unless 조건문 -->
<p th:unless="${user.gender == 'male'}">여성</p>

 

 

4. 속성

<!-- th:src라는 속성 -->
<img th:src="@{${imageUrl}}"/>

 

 

5. 링크 URL 처리

  • 단순 URL 처리
<!-- /hello라는 URL -->
<a th:href="@{/hello}>
  • 쿼리 파라미터를 포함하는 URL 처리
    • @{/hello(param1=${param1}, param2=${param2})}   ->   /hello?param1=value1&param2=value2
<a th:href="@{/hello(param1=${param1}, param2=${param2})}">URL included Query parameters</a>
  • 경로 변수가 포함된 URL 처리
    • @{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}   ->   /hello/value1/value2
 <a th:href="@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}">URL included Path Variables</a>
  • 경로 변수와 쿼리 파라미터가 포함된 URL 처리
    • @{/hello/{param1}(param1=${param1}, param2=${param2})}   ->   /hello/value1?param2=value2
<a th:href="@{/hello/{param1}(param1=${param1}, param2=${param2})}">path variable & query parameter</a>

 

 

6. 폼 처리

<!-- 객체(th:object로 request의 user 객체를 잡음) -->
<form action="#" th:object="${user}" method="post">
    <!-- th:object로 선택한 user 객체의 속성(username, password)을 *{ }로 접근 -->
    <!-- *{...}은 Selection expression(선택 표현식)이라고 한다 -->
    <!-- 즉, ${user.username} == *{username} -->
    <input type="text" th:field="*{username}"/>
    <input type="text" th:field="*{password}"/>
    <button type="submit">로그인</button>
</form>

 

 

7. 메시지 처리

메시지 처리를 위한 코드를 다음과 같이 작성했습니다

...
<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
...

 

messages.properties라는 임의의 message source에 아래와 같이 home.welcome 값이 있다고 해봅시다

...
home.welcome = ¡Bienvenido a nuestra tienda de comestibles!
...

 

그렇다면 메시지 처리 코드의 결과는 다음과 같습니다

...
<p>¡Bienvenido a nuestra tienda de comestibles!</p>
...

 

위의 결과는 정적인 데이터만을 나타냅니다. 그러나 만약 다음과 같이

...
<p>¡Bienvenido a nuestra tienda de comestibles, HONG KILL DONG!</p>
...

접속한 사람의 이름을 포함하여 나타내는, 동적인 데이터를 나타내려면 어떻게 해야하겠습니까?

 

이 말은 아래와 같이 messages source에 파라미터를 추가해야 함을 말합니다.

...
home.welcome=¡Bienvenido a nuestra tienda de comestibles, {0}!
...

메시지 처리 코드에 파라미터를 추가해주면 다음과 같습니다

<!-- HTTP session 속성 중 user.name을 파라미터라고 해보자 -->
...
<p th:text="#{home.welcome(${session.user.name}}">Welcome to our grocery store!</p>
...

 

 

 

 

 

Thymeleaf 속성 우선 순위(Attribute Precedence)

Thymeleaf에서는 속성들이 실행되는 순서에 있어서 우선 순위가 존재합니다.

Thymeleaf 속성들의 우선 순위는 다음과 같습니다.

 

 

 

Order       Feature                                                                                                         Attributes

1 Fragment inclusion th:insert
th:replace
2 Fragment iteration th:each
3 Conditional evaluation th:if
th:unless
th:switch
th:case
4 Local variable definition th:object
th:with
5 General attribute modification th:attr
th:attrprepend
th:attrappend
6 Specific attribute modification th:value
th:href
th:src
...
7 Text (tag body modification) th:text
th:utext
8 Fragment specification th:fragment
9 Fragment removal th:remove

 


 

 

 

 

 


Reference

* https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#standard-expression-syntax

 

Tutorial: Using Thymeleaf

1 Introducing Thymeleaf 1.1 What is Thymeleaf? Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide a

www.thymeleaf.org

* https://jddng.tistory.com/248

* http://progtrend.blogspot.com/2019/05/thymeleaf.html

* https://jddng.tistory.com/231

반응형