-
Thymeleaf란? ( + Thymeleaf 사용법, 문법 맛보기)Spring Framework 2022. 1. 13. 00:01
스프링 부트를 시작하기 위해 Thymeleaf라는 템플릿 엔진 의존성을 추가하였습니다.
또한 템플릿 엔진에 대해서 알아보았고 Spring Boot가 자동 환경 설정을 지원하는 Thymeleaf, Mustache, FreeMarker, Groovy에 대한 비교도 해보았습니다
https://junuuu.tistory.com/55?category=968779
이제 Thymeleaf에 대해 알아보겠습니다
공식 홈페이지에는 아래와 같이 소개됩니다.
Thymeleaf는 HTML, XML, JavaScript, CSS 및 일반 텍스트까지 처리할 수 있는 웹 및 독립 실행형 환경 모두를 위한 서버 사이드 Java 템플릿 엔진입니다.
Thymeleaf의 주요 목표로는 사용자의 개발에 우아하고 자연스러운 템플릿을 가져오도록 하는 것입니다.
이를 달성하기 위해 프로토타입으로 사용되는 템플릿에 영향을 미치지 않는 방식으로 템플릿 파일에 논리를 삽입하는 Natural Templates의 개념을 기반으로 합니다.
이를 통해 디자인 커뮤니케이션이 향상되고 디자인 팀과 개발 팀 간의 격차가 해소됩니다.
Natural templates
Thymeleaf로 작성된 HTML 템플릿은 여전히 HTML처럼 보이고 작동합니다.
<table> <thead> <tr> <th th:text="#{msgs.headers.name}">Name</th> <th th:text="#{msgs.headers.price}">Price</th> </tr> </thead> <tbody> <tr th:each="prod: ${allProducts}"> <td th:text="${prod.name}">Oranges</td> <td th:text="${#numbers.formatDecimal(prod.price, 1, 2)}">0.99</td> </tr> </tbody> </table>
th:text
th:each
#{...}
${...}
에 대해서는 밑에서 다루어 보겠습니다.
Dialects: The Standard Dialect
사용자 확장성을 제공하기 위하여 Dialects을 제공합니다. 템플릿이 세부 수준으로 처리되는 방식을 정의하고 사용자 지정할 수 있습니다.
기본적으로 Thymeleaf의 핵심 라이브러리는 대부분의 사용자에게 충분할 Standard Dialect를 제공합니다.
th 접두사를 통해 템플릿이 사용되는 시기를 식별할 수 있습니다.
<span th: text="...">
Standard Expression syntax(표준 표현 구문)
${...} : 변수 표현식
*{...} : 선택 표현식
#{...} : 메시지 표현식
@{...} : 링크 표현식
~{...} : 프래그먼트 표현식
Some basic attributes(몇 가지 기본 속성)
<p th:text="#{msg.welcome}">Welcome everyone!</p>
th:text 태그의 본문을 대체합니다.
<li th:each="book : ${books}" th:text="${book.title}">En las Orillas del Sar</li>
th: each 표현식에서 반환된 배열이나 목록에 지정된 횟수만큼 요소를 반복하고 반복 요소에 대한 내부 변수도 생성합니다.
실제로 실습하면서 배우고 싶으시다면 아래의 링크를 참조하세요!
저는 공식문서를 읽는 것을 좋아하진 않기 때문에 실습을 진행해보도록 하겠습니다.
http://itutorial.thymeleaf.org/
그러면 실습을 진행해보겠습니다
1. 정적인 템플릿 동적인 템플릿으로 변경하기(th:text)
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 2</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Solution for exercise 1: bean values</h1> <h2>Product information</h2> <dl> <dt>Product name</dt> <dd th:text="${product.description}">Red chair</dd> <dt>Product price</dt> <dd th:text="${product.price}">350</dd> <dt>Product available from</dt> <dd th:text="${product.availableFrom}">28-Jun-2013</dd> </dl> </body> </html>
th:text와 변수표현식${...}을 사용하여 product 객체에서 description, price, availableFrom을 가져온다고 가정했을 때 위와 같은 코드는 어떻게 동작할까요?
만약 product 객체가 없다면 Red chair, 350, 28-Jun-2013이 출력이 되며
만약 product 객체에서 값을 가져온다면 해당하는 값이 텍스트로 들어가게 되어 출력됩니다.
해당 값이 Wooden wardrobe with glass doors, 850, Mon Feb 18 00:00:00 UTC 2013이라고 가정하겠습니다.
2. 간단한 포멧팅 적용(Simple Formatting)
만약에 값을 가져올 때 정수를 실수로 변경하거나 날짜를 정해진 형식으로 만들기 위해서 어떻게 해야 할까요?
850을 850.00으로 표현하고 싶다면 ${product.price}를 ${#numbers.formatDecimal(product.price, 1, 2)}로 변경해야 합니다.
또한 Mon Feb 18 00:00:00 UTC 2013을 연도로 표기하고 싶다면 ${product.availableFrom}을 ${#dates.format(product.availableFrom, 'dd-MMM-yyyy')}으로 변경하면 됩니다.
3. 문자열 접합(String concatenation)
우리가 만약 850.00앞에 $문자열을 붙이고 싶다면 어떻게 해야 할까요?
${#numbers.formatDecimal(product.price, 1, 2)} 을 ${'$' + #numbers.formatDecimal(product.price, 1, 2)}으로 변경하면 됩니다.
4. escaped and unescaped text
th:text를 사용하면 html이 그대로 출력되며 th:utext를 사용하면 html이 적용되어 출력됩니다.
<div th:text="${html}">의 결과
This is an <em>HTML</em> text. <b> Enjoy yourself! </b>
<div th:utext="${html}">의 결과
This is an HTML text. Enjoy yourself!
5. 반복문(iteration)
th:each = "product : ${productList}를 사용합니다.
등등 여러 가지 튜토리얼이 쉽게 정리되어있습니다.
더 알아보고 싶다면 직접 해보시면 도움이 될 것 같습니다.
저는 나중에 사용할 일이 생긴다면 더 실습하여 사용해보겠습니다.
출처
https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html
'Spring Framework' 카테고리의 다른 글
스프링 부트 - 회원 관리 예제 실습(회원 서비스 개발) (0) 2022.02.13 스프링 부트 - 회원 관리 예제 실습(회원 도메인과 리포지토리 생성) (0) 2022.01.26 ThymeLeaf vs Mustache vs Groovy vs FreeMarker (0) 2022.01.12 서블렛(Servlet)이란? (0) 2022.01.09 템플릿엔진이란? (0) 2022.01.07