728x90
반응형
* URL 링크 표현식 (@{링크})
th:href="@{URL_LINK}"
* 리터럴 대체 (|문자열|)
- 문자와 표현식 등의 분리된 형태를 리터럴 대체 문법을 이용해 간단하게 처리
th:text="'Hello '" + ${user.name} + '!'"
th:text="|Hello ${user.name}!|"
* 변수 표현식 (${변수명})
- 모델객체에 포함된 변수나 타임리프 변수를 조회
th:text="${user.age}"
* 외부 자원 표현식 (#{변수명})
- 메시지, 프라퍼티 등 외부 자원의 데이터 표시
th:text="#{msg.reg.success}"
* 기본 객체들
- #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>.
* 편의 객체
- HTTP 요청 파라미터 (param): ${param.paramData}
- session: ${session.sessionData}
- 스프링 빈(@스프링빈): ${@helloWorld.init('Hello World')}
* 유틸리티 객체들
- #execInfo: information about the template being processed.
- #messages: methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
- #uris: methods for escaping parts of URLs/URIs
- #conversions: methods for executing the configured conversion service (if any).
- #dates: methods for java.util.Date objects: formatting, component extraction, etc.
- #calendars: analogous to #dates, but for java.util.Calendar objects.
- #temporals: methods for LocalDate, LocalDateTime, Instance in java8+ version
- #numbers: methods for formatting numeric objects.
- #strings: methods for String objects: contains, startsWith, prepending/appending, etc.
- #objects: methods for objects in general.
- #bools: methods for boolean evaluation.
- #arrays: methods for arrays.
- #lists: methods for lists.
- #sets: methods for sets.
- #maps: methods for maps.
- #aggregates: methods for creating aggregates on arrays or collections.
- #ids: methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
예1) #calendar
WebContext ctx =
new WebContext(request, response, servletContext, request.getLocale());
ctx.setVariable("today", Calendar.getInstance());
templateEngine.process("home", ctx, response.getWriter());
<p>
Today is: <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 May 2011</span>
</p>
예2) #temporals
model.addAttribute("localDataTime", LocalDateTime.now());
<span th:text="${#temporals.format(localDataTime,'yyyy-MM-dd HH:mm:ss')}">13 May 2011</span>
<span th:text="${#temporals.day(localDataTime)}">13 May 2011</span>
* 연산자
* 비교 연산자
- Comparators: >, <, >=, <= (gt, lt, ge, le)
- Equality operators: ==, != (eq, ne)
* 조건 연산자
- If-then: (if) ? (then)
- If-then-else: (if) ? (then) : (else)
- Default: (value) ?: (defaultvalue)
* 스페셜 토큰
- No-Operation: _
(${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
* 스페셜 토큰 예제
: nullData가 null일 경우 타임리프가 실행되지 않는 것처럼 처리되어 'Alternative Text'가 주입된다.
<span th:text="${nullData}?: _">Alternative Text</span>
* 속성값 설정
- th:* 을 이용해서 HTML 속성 값이 없으면 생성, 존재하면 대체한다.
렌더링 전: <input type="button" value="Do it!" class="btn" th:attrappend="class=${' ' + cssStyle}" />
렌더링 후: <input type="button" value="Do it!" class="btn warning" />
- boolean 속성값 설정
th:async | th:autofocus | th:autoplay |
th:checked | th:controls | th:declare |
th:default | th:defer | th:disabled |
th:formnovalidate | th:hidden | th:ismap |
th:loop | th:multiple | th:novalidate |
th:nowrap | th:open | th:pubdate |
th:readonly | th:required | th:reversed |
th:scoped | th:seamless | th:selected |
<input type="checkbox" name="active" th:checked="false" />
* 반복문 (th:each="변수[, 상태변수] : ${콜렉션객체}")
- 상태변수의 속성. 다른 속성은 직관적으로 알 수 있고, current 데이터가 조금 낯선데 이건 설명처럼 변수와 같은 속성이다. 그래서 변수와 비교하면 true가 나온다.
- The current iteration index, starting with 0. This is the index property.
- The current iteration index, starting with 1. This is the count property.
- The total amount of elements in the iterated variable. This is the size property.
- The iter variable for each iteration. This is the current property.
- Whether the current iteration is even or odd. These are the even/odd boolean properties.
- Whether the current iteration is the first one. This is the first boolean property.
- Whether the current iteration is the last one. This is the last boolean property.
<table>
<thead><tr>
<th>아이디</th><th>index</th>
<th>count</th><th>even</th>
<th>odd</th><th>first</th>
<th>last</th><th>current</th><th>size</th>
</tr></thead>
<tbody>
<tr th:each="user, userStat : ${list}">
<td><span th:text="${user.userId}"></span></td>
<td><span th:text="${ userStat.index }"></span></td>
<td><span th:text="${ userStat.count }"></span></td>
<td><span th:text="${ userStat.even }"></span></td>
<td><span th:text="${ userStat.odd }"></span></td>
<td><span th:text="${ userStat.first }"></span></td>
<td><span th:text="${ userStat.last }"></span></td>
<td><span th:text="${ userStat.current == user }"></span></td>
<td><span th:text="${ userStat.size }"></span></td>
</tr>
</tbody>
</table>
* 단순 조건 평가
1. th:if, th:unless
<a href="comments.html"
th:href="@{/product/comments(prodId=${prod.id})}"
th:if="${not #lists.isEmpty(prod.comments)}">view</a>
<a href="comments.html"
th:href="@{/comments(prodId=${prod.id})}"
th:unless="${#lists.isEmpty(prod.comments)}">view</a>
2. th:switch
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p> <-- default option
</div>
* th:text
1. html 태그 안에 들어갈 때
th:text="${data}"
2. html 영역 안에 들어갈 때
[[${data}]]
3. unescape 하기
- th:text로 렌더링되는 값들은 escape 되어 html 엔티티로 제공된다.
예를 들어 서버사이드에서 <b>Hello</b> 로 값을 전달했을 때, th:text="${}" 에 렌더링 될 때의 값은
<b>Hello</b> 가 된다.
unescape하기 위해서는 다음과 같이 하면 된다.
th:utext="${data}"
[(${data})]
* th:with (지역변수)
- 지역변수로 사용할 수 있으며, 지역 변수는 선언한 태그 내부에서만 유효
<tr th:with="user=${users[0]}>
<td th:text="${user.name}">Dorothy</td>
</tr>
728x90