[docs] 타임리프 기본 문법(context , value)

반응형
반응형

[이 문서는 타임 리프 문서를 재 구성하여 만들었습니다]

 

간단 사용 방법

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

<p>Today is: <span th:text="${today}">13 february 2011</span></p>

 

위의 내용과 비슷하게 사용되어진다. 

th:utext와 th:text는 추후에 알아볼예정

 

  • 간단 사용 방법
    • 변수: ${...}
    • 세션 사용: *{...}
    • 메시지: #{...}
    • URL: @{...}
    • 프레그먼트: ~{...}

아마 맨 위는 다른거들에 포함이 되지 않으면 ${...}를 이용하는 듯 싶다.

혹은 모든 변수에 이용이 가능하다 정도?

 

 

메시지 사용방법 : #{...}를 추가하면 된다.

하지만 이렇게만 만들면 재미가 없다??? 

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

메시지에는 이런식으로 추가

 

사용 방법 :

 

일반 (원래는 context임) : 

 

전에 jsp를 사용했을 때, 주로 db에서 가져 온 값들을 사용한듯 한 경험을 미뤄봤을때,

타임리프도 비슷한 용도로 사용하지 않을까? 유추해본다.

<p>Today is: <span th:text="${today}">13 february 2011</span>.</p>

 

 

이 뜻은...

ctx.getVariable("today");

이건 잘 모르지만. context라는 클래스에서 값을 가져오든 것 같다. 그것이 이름이 today인것 같고,..

 

또 이렇게도 사용할 수 있다.

<p th:utext="#{home.welcome(${session.user.name})}">
  Welcome to our grocery store, Sebastian Pepper!
</p>

메시징안에 값을 넣어서 보낼 수 있다.

반대는 되지 않는걸로 알고는 있지만... 추후에 된다고 나온다면, 정정할 예정..

 

또, 이것들은 이런 식으로 사용할 수 있다.

  • #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.

이 부분은 잘 모르겠어서 영문으로 남겨두겠다.

대충 유추해보자면... 리퀘스트, 리스펀스, 세션등 다양한 식을 제공하는데 #을 붙여서 사용이 되는듯 하다. (이 부분은 더 공부를 해야겠다고 느껴진다.)

 

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

세션 : *{...} 

  <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>
  <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
  <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
  <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>

이거와 동일하다.

 

 

#Object 표현식이라는게 존재한다고 하는데... 잘 모르기 때문에 pass...

위에 링크 남겨둠... 아무래도 #session과 *{...}는 다른 의미 같다.

 

URL

 

  • 페이지 기준 : user/login.html
  • 문맥 기준: /itemdetails?id=3 
    • 주로 db같은 데에서 값을 검색할때 사용하는 것 같음
  • 서버 기준 : ~/billing/processInvoice 
    • 같은 서버의 다른 문맥의 URL을 허용한다고 함.
  • 프로토콜 기준 : //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/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{/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>

이런식으로 사용된다.

orderId라는곳에 o.id를 값으로 받아서 전달이 가능한 것 같다.

<p>Please select an option</p>
<ol>
  <li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li>
  <li><a href="order/list.html" th:href="@{/order/list}">Order List</a></li>
  <li><a href="subscribe.html" th:href="@{/subscribe}">Subscribe to our Newsletter</a></li>
  <li><a href="userprofile.html" th:href="@{/userprofile}">See User Profile</a></li>
</ol>

메뉴 만드는 코드

 

 

프레임워크 :

프레임 워크는 템플릿 위주로 쉽게 이동할 수 있는 방법이라고 한다.

아무래도 프레임워크라는 뜻이 뼈대, 조각이라는 뜻인것으로 미뤄봤을 때. 프레임워크를 만드는 느낌이 든다.

th.insert 혹은 th.replace기 존재.

<div th:insert="~{commons :: main}">...</div> 

<div th:with="frag=~{footer :: #main/text()}">
  <p th:insert="${frag}">
</div>

이런식으로도 사용한다고 함...

 

 

 

리터럴 - 위키백과, 우리 모두의 백과사전

위키백과, 우리 모두의 백과사전. 컴퓨터 과학 분야에서 리터럴(literal)이란 소스 코드의 고정된 값을 대표하는 용어다. 거의 모든 프로그래밍 언어는 정수, 부동 소수점 숫자, 문자열, 불린 자료�

ko.wikipedia.org

  • 리터럴  (흔히 생각 하는상수) 
    • 텍스트 리터럴: '하나요', '다른 하나',…
    • 숫자 리터럴: 0, 34, 3.0, 12.3,…
    • 불린(참 거짓) 리터럴: true, false
    • 널 리터럴: null
    • 리터럴 토큰: one, sometext, main,…

텍스트는 "ㄴㄴㄴㄴ"이런거 가능하고

숫자는 123 이런거

불린은 false , true 이런거 예제 에서는 == 비교를 통해 사용하는 예시가 존재한다,

null은 null

리터럴 토큰은 리터럴을 토큰으로 만들어서 사용가능하다고 한다.

<div th:class="content">...</div>

대신에

<div th:class="'content'">...</div>

잘 보시면 content 좌우로 ' '(작은 따움표)가 있는것을 확인 할 수 있다.

 

 

  • 텍스트 연산자:
    • 문자 : +
    • 리터럴 분리: |The name is ${name}|

리터럴 분리는 사용해봐야 알듯 싶다.

<span th:text="|Welcome to our application, ${user.name}!|">

==

<span th:text="'Welcome to our application, ' + ${user.name} + '!'">

 

  • 숫자(산수) 연산자:
    • 이진 연산 : +, -, *, /, %   
    • 마이너스 표시 (단일 오퍼레이터) : -

산수 처리 가능!

<div th:with="isEven=${prodStat.count % 2 == 0}">
  • 불린 연산자:
    • 이진 오퍼레이터: and, or
    • 부정 불린값 (단일 오퍼레이터): !, not
<tr th:class="${row.even}? (${row.first}? 'first' : 'even') : 'odd'">
  ...
</tr>
  • 비교와 동등:
    • 비교 : >, <, >=, <= (gt, lt, ge, le)
    • 동등 오퍼레이터: ==, != (eq, ne)
<div th:if="${prodStat.count} &gt; 1">
<span th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')">
  • 조건 연산자:
    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ?: (defaultvalue)
<p>
  Name: 
  <span th:text="*{firstName}?: (*{admin}? 'Admin' : #{default.username})">Sebastian</span>
</p>
  • 특별 토큰:
    • No-Operation: _

만약에 특정 무언가를 사용하지 못한다면... 

<span th:text="${user.name} ?: _">no user authenticated</span>

이런식으로 표시....

아마 username이 없으면 뒤에꺼를 사용하겠다라는 의미 같다.

 

 

여기까지가 4.3부터 4.13까지의 내용입니다.

아마 ${} 시리즈를 많이 사용할것 같고..

나머지는 틈틈히 사용할것 같은 느낌...

반응형

댓글

Designed by JB FACTORY