카테고리 없음

Thymeleaf 타임리프 3.0X

k9e4h 2023. 1. 26. 17:37

공식문서

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

 

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

 

1. Thymeleaf 소개

1.1 Thymeleaf란?

modern server-side Java template engine

우아하고 몹시 유지가능하게 템플릿을 만드는 방법을 제공하는것이 목표

Natural Template 개념에 기반

1.2 thymeleaf가 처리할 수 있는 tmplate의 종류

Markup Mode(HTML, XML)

textual Mode(TEXT, JAVASCRIPT, CSS, RAW)

     
Markup template mode html html5, html4, xhtml
유효성 검사 X, 출력가능한 최대 범위까지 코드/구조 작성가능
xml unclose tags, unquoted attributes 등을 검사하기때문에 xml input만 허용됨
xml 스키마나 DTD에 대한 유효성 검사는 하지 않음
Textual template mode text  
Javascript HTML 파일에서 수행할 수 있는 것과 동일한 방식으로 JavaScript 파일 내에서 모델 데이터를 사용할 수 있음을 의미합니다.
그러나 특수 이스케이프 또는 자연 스크립팅과 같은 JavaScript 관련 통합이 있습니다.
JAVASCRIPT 템플릿 모드는 텍스트 모드로 간주되므로 TEXT 템플릿 모드와 동일한 특수 구문을 사용합니다.
css CSS 템플릿 모드는 텍스트 모드로 간주되므로 TEXT 템플릿 모드와 동일한 특수 구문을 사용합니다.
raw raw 모드는 템플릿을 처리하지 않는다.
가공되지 않은 리소스(files, url, response 등)을 처리할때 사용

1.3 Dialets: The Standard Dialet (표준 방언..?)

Thymeleaf는 템플릿 엔진 프레임워크이다. 

마크업 아티팩트에 논리를 적용하는 객체를 프로세서라고 하며, 이러한 프로세서들의 집합은 일반적으로 방언으로 구성

standard dialet의 대부분은 attribute processor이다.

 

standard dialet 사용하지 않는 JSP의 경우

<form:inputText name="userName" value=${user.name}>

standard dialet 을 사용하는 경우

<input type="text" name="userName" value="James Carrot" th:value="${user.name}">

 

standard dialet을 사용하면 정확하게 brower에 표시하는 것 뿐만 아니라 특정한 attribute value를 넣어 template processing 할때 default 값으로 보여줄 수 있다.(ex : user.name이 셋팅되기 전에 James Carrot으로 보여줌)

 

이렇게 하면 디자이너와 개발자가 동일한 템플릿 파일에서 작업하고 정적 프로토타입을 작업 템플릿 파일로 변환하는 데 필요한 노력을 줄일 수 있습니다. 이를 수행하는 기능은 Natural Templating이라는 기능입니다.

디자이너가 value를 넣어 놓으면 개발자가 th:value를 셋팅하기 전에도 화면이 보이니까!

 

2. 가상 grocery에 대한 좋은 테마 (예제 프로젝트 설명 단원)

예제 코드 - https://github.com/thymeleaf/thymeleafexamples-gtvg

2-1. grocery 웹사이트 설명

2-2. template engine 생성 및 설정

Template Resolver

Template Engine

3. Using Texts

3.1 다국어

브라우저는 th:text와 같이 이해하지 못하는 모든 속성을 무시합니다

- 외부의 텍스트 사용하기 

분리된 파일(일반적으로 .properties 파일)에 있는 값으로 대체하여 사용할 수 있다.

외부화된 텍스트를 message라고 부른다.

#{home.welcom} 으로 사용

Standard Dialect와 다른점 : 

th:text - host tag에 replace

#{home.welcome} - home.welcome이 locale에 key로 존재하는지 확인

IMessageResolver를 implement하여 externalized text의 위치를 정의가능하다. 

일반적으로 .properties 파일을 이용하고 동일한 template 이름의 파일을 찾는다

1. template 경로
/WEB-INF/templates/home.html
2. i18n 경로
/WEB-INF/template/home_en.properteis
/WEB-INF/template/home_es.properteis
/WEB-INF/template/home_ko.properteis
3. home_es.properteis 예시
home.welcome=¡Bienvenido a nuestra tienda de comestibles!

Contexts

variables map의 template engine을 실행하기 위한 데이터와 locale 정보를 가지고있다

WebContexts는 ServletApi를 기반으로한다.

template에서 request parameters, request, session, application attribute를 사용하기 위해서는 3가지 방법이 있다.

${x} : request attribute
${param.x} request parameter called x
${session.x} session attribute called x
${application.x} servlet context attribute x

 

3.2 More on texts and variables

Unescaped Text

home.welcome=Welcome to our <b>fantastic</b> grocery store!
위와 같은 경우 th:utext를 이용하여 처리한다.
<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>

${...} 는 변수 표현식 / OGNL(Object-Graph Navigation Language) 라고 부른다.

${user.name}은 user라는 변수의 getName() 메서드를 호출하는 것이다.

 

4. Standard Express Syntax

4.1 Message

message에 변수 넣을 수 있음

message 키 자체도 변수로 사용할수있음

4.2 Variable

1. point(.)를 이용하여 propertey get
${person.father.name}
2. bracket([])+ single quotes
${person['father']['name']}
3. object가 map이라면 dot + bracket 으로 사용할 수 있음
${countriesByCode.ES}
${personsByName['Stephen Zucchini'].age}
4. array, collection 의 경우 index 사용 가능
${personsArray[0].name}
5. method 호출 가능
${person.createCompleteName()}
${person.createCompleteNameWithSeparator('-')}

 

 

Expression Basic Object 

- 부록 참고해서 사용법 확인할 것 부록A

  • #ctx: the context object.
  • #vars: the context variables.
  • #locale: the context locale.
  • #request: (only in Web Contexts) the HttpServletRequest object.
  • #response: (only in Web Contexts) the HttpServletResponse object.
  • #session: (only in Web Contexts) the HttpSession object.
  • #servletContext: (only in Web Contexts) the ServletContext object.
Established locale country: <span th:text="${#locale.country}">US</span>.

Expression Utility Objects

- 부록 참고해서 사용법 확인할 것 부록B

이것저것들

 

4.3 Expressions on selections

선택 영역에 대한 표현식 *{...}

<div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
    <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>

상위 div에서 th:object로 영역을 지정해줌

하위 p 태그에서 session.user를 또 선언할 필요없이 사용가능

 

4.4 Link URLs

절대경로 URLs : http://www.thymeleaf.org 

상대경로 URLs : 

Page-relative : user/login.html

Context-relative: /itemdetails?id=3 

Server-relative: ~/billing/processInvoice

Protocal-relative URLs : //code.jquery.com/jquery-2.0.3.min.js

<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" 
   th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>
   
<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

th:href 는 attribute를 변경한다 : 일단 처리되면 a tag의 href에 셋팅할 값을 설정한다.

th:href에서는 URL parameter를 위해 표현식을 사용할 수 있고 url encoding은 자동으로 적용된다. ex) ${o.id}

여러개의 파라미터가필요할 경우 comma를 이용하여 구분할 수 있다. ex) @{/order/{orderId}/details(orderId=${execId}, execType='FAST')}

relative URLs은 /로 시작하고 conext name을 자동적으로 prefix로 가진다.

 

4.5 Fragments

Fragments는 markup 조각을 재표현하고 template으로 쉽게 옮기는 방법을 제공한다. 파편을 복제하고 다른 template의 arguments로 옮길 수 있게한다.

 

일반적으로 fragments를 삽입하는 방법은 th:insert 또는 th:replace를 사용하는 것이다.

어느 위치에나 사용될 수 있다.

다음 섹션에서 자세히 배웁시다..

 

4.6 Literals(표현방법)

Text literals : single quotes / ---> escape : \'   ----> th:text="'working web application'"

Number : ----> th:text="2013+3"

boolean : th:if="${user.isAdmin()}"

null : th:if="${variable.somthing} == null"

literal token : th:text, th:if .. 등등 일반

 

4.7 Appending texts

<span th:text="'The name of the user is ' + ${user.name}">

4.8 Literal 치환

Literal 치환은 변수를 포함한 String의 formatting을 + 기호 없이도 쉽게하도록한다.

|~~~| 내부에 ${...}, *{...}, #{...}도 사용 가능

Literal 치환 사용한 경우
<span th:text="|Welcome to our application, ${user.name}!|">
Literal 치환 사용하지 않는 경우
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">

4.9 산술 계산

+, = , * , / , % 사용 가능 / 어떤 OGNL 내에서 사용할 수 있음

/, %는 textual 중에서 다르게 사용될 수 있음

 

4.10 비교 또는 동급

>,<,>=,<= , ==, != 

xml에서는 <,> 를 사용할 수 없다. &lt, &gt로 대체해서 사용할 것

 

4.11 조건문

삼항연산자 사용 가능, else 구문 생략 가능

조건이 null인 경우 false 가 됨, 

else 구문 생략
row.even이 존재하는 경우 alt, 아닌 경우 class 생략
<tr th:class="${row.even}? 'alt'">
  ...
</tr>

 

4.12 default expressions (Elvis operator)

Groovy 같은 language에서 Elvis operator와 같이 사용

- null 처리 방법 

<div th:object="${session.user}">
  ...
  <p>Age: <span th:text="*{age != null}? *{age} : '(no age specified)'">27</span>.</p>
</div>

4.13 No-Operation token

undersore symbol (_)

조건에 따라 속성이 아예 없는 것처럼 처리하기 위해서 사용한다.

No-Operation token 사용한 경우
<span th:text="${user.name} ?: _">no user authenticated</span>
No-Operation token 사용하지 않은 경우
<span th:text="${user.name} ?: 'no user authenticated'">...</span>

4.14 Data 전환 / 포맷팅

java의 date 형식을 string type으로 변환하여 사용할 수 있음
<td th:text="${{user.lastAccessDate}}">...</td>

4.15 preprocessing

데이터를 수정할 표현식 이전에 실행되는 것이다.

 

 

build on ~위에 쌓다

hava (somebody/something) in mind (for something) ~을 염두에 두다

respect

extent (심각성) 정도, (지역) 규모

extensible 확장가능한

level of detail 세부적인 수준, 정밀도

comprised of ~로 구성된

entirely 전적으로, 완전히

definitely 확실히

explicitly 명쾌하게

substitue 교체하다

in charge of ~를 담당하여

scenario

so on  곧, 머지않아,

just as ~와 마찬가지로

parenthese 괄호

 

반응형