Thymeleaf
Documentation - Thymeleaf
- Server Side Rendering (SSR)
- Natural Template
- Spring 통합 지원
Thymeleaf 사용 선언
<html xmlns:th="http://wwww.thymeleaf.org">
th:text
- HTML의 Content에 데이터를 출력
- 기본적으로 escape 처리 제공
<span th:text="${data}"></span>
<span>[[${data}]]</span>
th:utext
<span th:utext="${data}"></span>
<span>[(${data})]</span>
- escape 기능 사용하지 않고 적용
- ⚠️ 가급적이면 사용하지 않는것을 추천
th:inline
<span th:inline="none">[[...]] vs [(...)]</span>
th:inline="none"
- 해당 Tag안에서는 Thymelefa가 해석하지 말라는 옵션
SpringEL - ${…}
${...}
Object
${user.username}
${user['username']}
${user.getUsername()}
List
${users[0].username}
${users.get(0).getUsername()}
${users[0]['username']}
${users[0].getUsername()}
Map
${userMap['userA'].username}
${userMap.get("userA").getUsername()}
${userMap['userA']['username']}
${userMap['userA'].getUsername()}
예시
<ul>Object
<li>${user.username} = <span th:text="${user.username}"></span></li>
<li>${user['username']} = <span th:text="${user['username']}"></span></li>
<li>${user.getUsername()} = <span th:text="${user.getUsername()}"></span></li>
</ul>
<ul>List
<li>${users[0].username} = <span th:text="${users[0].username}"></span></li>
<li>${users[0]['username']} = <span th:text="${users[0]['username']}"></span></li>
<li>${users[0].getUsername()} = <span th:text="${users[0].getUsername()}"></span></li>
</ul>
<ul>Map
<li>${userMap['userA'].username} = <span th:text="${userMap['userA'].username}"></span></li>
<li>${userMap['userA']['username']} = <span th:text="${userMap['userA']['username']}"></span></li>
<li>${userMap['userA'].getUsername()} = <span th:text="${userMap['userA'].getUsername()}"></span></li>
</ul>
th:with
- 지역변수 선언해서 사용할 수 있다.
- ⚠️ 선언한 Tag안에서만 사용 가능
<div th:with="firstUser=${users[0]}">
<p>첫 사용자 이름은 <span th:text="${firstUser.username}"></span>
</div>
기본 객체 제공
${#request}
- HttpServletRequest
- RequestFacade
${#response}
- HttpServletResponse
- ResponseFacade
${#sessions}
- HttpSession
- StandardSessionFacade
${#servletContext}
- ServletContext
- ApplicationContextFacade
${#locale}
<ul>
<li>request = <span th:text="${#request}"></span></li>
<li>response = <span th:text="${#response}"></span></li>
<li>session = <span th:text="${#session}"></span></li>
<li>servletContext = <span th:text="${#servletContext}"></span></li>
<li>locale = <span th:text="${#locale}"></span></li>
</ul>
편의 객체 제공
${param.paramData}
${session.sessionData}
${@helloBean.hello('Spring!')}
<ul>
<li>Request Parameter = <span th:text="${param.paramData}"></span></li>
<li>session = <span th:text="${session.sessionData}"></span></li>
<li>spring bean = <span th:text="${@helloBean.hello('Spring!')}"></span></li>
</ul>
유틸리티 객체와 날짜
Tutorial: Using Thymeleaf
- 문자, 숫자, 날짜, URI등을 편리하게 다루는 다양한 유리틸리 객체들을 제공한다.
${#message}
${#uris}
${#dates}
${#calendars}
${#temporals}
- Java8 날짜 서식 지원
<ul>
<li>default = <span th:text="${localDateTime}"></span></li>
<li>yyyy-MM-dd HH:mm:ss = <span th:text="${#temporals.format(localDateTime, 'yyyy-MM-dd HH:mm:ss')}"></span></li>
</ul>
<ul>
<li>${#temporals.day(localDateTime)} = <span th:text="${#temporals.day(localDateTime)}"></span></li>
<li>${#temporals.month(localDateTime)} = <span th:text="${#temporals.month(localDateTime)}"></span></li>
<li>${#temporals.monthName(localDateTime)} = <span th:text="${#temporals.monthName(localDateTime)}"></span></li>
<li>${#temporals.monthNameShort(localDateTime)} = <span th:text="${#temporals.monthNameShort(localDateTime)}"></span></li>
<li>${#temporals.year(localDateTime)} = <span th:text="${#temporals.year(localDateTime)}"></span></li>
<li>${#temporals.dayOfWeek(localDateTime)} = <span th:text="${#temporals.dayOfWeek(localDateTime)}"></span></li>
<li>${#temporals.dayOfWeekName(localDateTime)} = <span th:text="${#temporals.dayOfWeekName(localDateTime)}"></span></li>
<li>${#temporals.dayOfWeekNameShort(localDateTime)} = <span th:text="${#temporals.dayOfWeekNameShort(localDateTime)}"></span></li>
<li>${#temporals.hour(localDateTime)} = <span th:text="${#temporals.hour(localDateTime)}"></span></li>
<li>${#temporals.minute(localDateTime)} = <span th:text="${#temporals.minute(localDateTime)}"></span></li>
<li>${#temporals.second(localDateTime)} = <span th:text="${#temporals.second(localDateTime)}"></span></li>
<li>${#temporals.nanosecond(localDateTime)} = <span th:text="${#temporals.nanosecond(localDateTime)}"></span></li>
</ul>
${#numbers}
${#strings}
${#objects}
${#bools}
${#arrays}
${#lists}
, ${#sets}
, ${#maps}
${#ids}
URL 링크 - @{…}
- Thymeleaf 에서 URL을 생성할 때는
@{...}
문법을 사용하면 된다.
- 상대경로, 절대경로, 프로토콜 기준을 표현할 수도 있다.
단순 URL
Query Parameter
@{/hello(param1=${param1}, param2=${param2})}
- /hello?param1=data1¶m2=data2
Path Variable
@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}
Path Variable + Query Parameter
@{/hello/{param1}(param1=${param1}, param2=${param2})}
- /hello/data1?param2=data2
<ul>
<li><a th:href="@{/hello}">basic url</a></li>
<li><a th:href="@{/hello(param1=${param1}, param2=${param2})}">hello query param</a></li>
<li><a th:href="@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}">path variable</a></li>
<li><a th:href="@{/hello/{param1}(param1=${param1}, param2=${param2})}">path variable + query parameter</a></li>
</ul>
Literal
- 문자 리터럴은 원칙상
'
로 감싸야 한다.
- 중간에 공백이 있어서 하나의 의미있는 토큰으로도 인식되지 않는다.
<ul>
<li>'hello' + ' world!' = <span th:text="'hello' + ' world!'"></span></li>
<li>'hello world!' = <span th:text="'hello world!'"></span></li>
<li>'hello ' + ${data} = <span th:text="'hello ' + ${data}"></span></li>
<li>리터럴 대체 |hello ${data}| = <span th:text="|hello ${data}|"></span></li>
</ul>
Literal Substitution
<ul>
<li>리터럴 대체 |hello ${data}| = <span th:text="|hello ${data}|"></span></li>
</ul>
Operation
No-Operation
_
- Thymeleaf가 실행지 않는 것 처럼 동작한다.
- HTML 내용 그대로 렌더링
<ul>
<li>산술 연산
<ul>
<li>10 + 2 = <span th:text="10 + 2"></span></li>
<li>10 % 2 == 0 = <span th:text="10 % 2 == 0"></span></li>
</ul>
</li>
<li>비교 연산
<ul>
<li>1 > 10 = <span th:text="1 > 10"></span></li>
<li>1 gt 10 = <span th:text="1 gt 10"></span></li>
<li>1 >= 10 = <span th:text="1 >= 10"></span></li>
<li>1 ge 10 = <span th:text="1 ge 10"></span></li>
<li>1 == 1 = <span th:text="1 == 10"></span></li>
<li>1 != 1 = <span th:text="1 != 10"></span></li>
</ul>
</li>
<li>조건식
<ul>
<li>(10 % 2 == 0)? '짝수':'홀수' = <span th:text="(10 % 2 == 0)? '짝수':'홀수'"></span></li>
</ul>
</li>
<li>Elvis 연산자
<ul>
<li>${data}?: '데이터가 없습니다.' = <span th:text="${data}?: '데이터가 없습니다.'"></span></li>
<li>${nullData}?: '데이터가 없습니다.' = <span th:text="${nullData}?: '데이터가 없습니다.'"></span></li>
</ul>
</li>
<li>No-Operation
<ul>
<li>${data}?: _ = <span th:text="${data}?: _">데이터가 없습니다.</span></li>
<li>${nullData}?: _ = <span th:text="${nullData}?: _">데이터가 없습니다.</span></li>
</ul>
</li>
</ul>
HTML 태그 속성 값 설정
속성 설정 - th:*
<input type="text" name="mock" th:name="userA" />
속성 추가
th:attrappend
<input type="text" class="text" th:attrappend="class=' large'" />
th:attrprepend
<input type="text" class="text" th:attrprepend="class='large '" />
th:classapeend
<input type="text" class="text" th:classappend="large" />
checked 처리 - tr:checked
<input type="checkbox" name="active" th:checked="true" />
<input type="checkbox" name="active" th:checked="false" />
반복 - th:each
th:each="user : ${users}"
- List, Iterable, Enumeration, Array, Map 모두 가능
- 단 Map일 경우, Map.Entry가 변수에 담긴다.
<table border="1">
<tr>
<th>username</th>
<th>age</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.username}">username</td>
<td th:text="${user.age}">0</td>
</tr>
</table>
반복 상태 유지 기능
th:each="user, userStat : ${users}"
- 변수명에 Stat을 붙인 변수에 자동으로 할당된다.
- 개발자가 직접 두번째 파라미터로 설정 가능
<table border="1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
<th>etc</th>
</tr>
<tr th:each="user, userStat : ${users}">
<td th:text="${userStat.count}">username</td>
<td th:text="${user.username}">username</td>
<td th:text="${user.age}">0</td>
<td>
index = <span th:text="${userStat.index}"></span>
count = <span th:text="${userStat.count}"></span>
size = <span th:text="${userStat.size}"></span>
even? = <span th:text="${userStat.even}"></span>
odd? = <span th:text="${userStat.odd}"></span>
first? = <span th:text="${userStat.first}"></span>
last? = <span th:text="${userStat.last}"></span>
current = <span th:text="${userStat.current}"></span>
</td>
</tr>
</table>
${userStat.index}
${userStat.count}
${userStat.size}
${userStat.even}
, ${userStat.odd}
${userStat.first}
, ${userStat.last}
${userStat.current}
조건부 평가
th:if
, th:unless
- 조건이 만족하지 않으면 태그 자체를 렌더링하지 않는다.
<table border="1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
</tr>
<tr th:each="user, userStat : ${users}">
<td th:text="${userStat.count}">1</td>
<td th:text="${user.username}">username</td>
<td>
<span th:text="${user.age}">0</span>
<span th:text="'미성년자'" th:if="${user.age lt 20}"></span>
<span th:text="'미성년자'" th:unless="${user.age ge 20}"></span>
</td>
</tr>
</table>
th:switch
, th:case
<table border="1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
</tr>
<tr th:each="user, userStat : ${users}">
<td th:text="${userStat.count}">1</td>
<td th:text="${user.username}">username</td>
<td th:switch="${user.age}">
<span th:case="10">10살</span>
<span th:case="20">20살</span>
<span th:case="*">기타</span>
</td>
</tr>
</table>
주석
표준 HTML 주석
- Thymeleaf가 렌더링 하지 않고, 그대로 남겨 둔다.
Thymeleaf Parser 주석
Thymeleaf Prototype 주석
- HTML파일을 그대로 열면, 주석처리가 된다.
- Thymeleaf 렌더링을 한 경우에만, 렌더링되어 보이게 된다.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>예시</h1>
<span th:text="${data}">html data</span>
<h1>1. 표준 HTML 주석</h1>
<h1>2. 타임리프 파서 주석</h1>
<span th:text="${data}">html data</span>
<h1>3. 타임리프 프로토타입 주석</h1>
</body>
</html>
블록 - <th:block>
- Thymeleaf 자체 유일한 태그
- Thymeleaf는 특성상 HTML 태그안에 속성으로 기능을 정의해서 사용
- 사용하기 애매한 경우에 th:block을 만들어서 속성으로 기능 사용
<th:block>
은 렌더링시 제거된다.
<th:block th:each="user : ${users}">
<div>
사용자 이름1 <span th:text="${user.username}"></span>
사용자 나이1 <span th:text="${user.age}"></span>
</div>
<div>
요약 <span th:text="${user.username} + ' / ' + ${user.age}"></span>
</div>
</th:block>
<div>
사용자 이름1 <span>UserA</span>
사용자 나이1 <span>10</span>
</div>
<div>
요약 <span>UserA / 10</span>
</div>
<div>
사용자 이름1 <span>UserB</span>
사용자 나이1 <span>20</span>
</div>
<div>
요약 <span>UserB / 20</span>
</div>
<div>
사용자 이름1 <span>UserC</span>
사용자 나이1 <span>30</span>
</div>
<div>
요약 <span>UserC / 30</span>
</div>
자바스크립트 인라인 - <script th:inline="javascript">
자바스크립트 인라인 사용 전
<script>
var username = [[${user.username}]];
var age = [[${user.age}]];
var username2 = "test username";
var user = [[${user}]];
</script>
<script>
var username = UserA;
var age = 10;
var username2 = "test username";
var user = BasicController.User(username = UserA, age = 10);
</script>
자바스크립트 인라인 사용한 경우
<script th:inline="javascript">
var username = [[${user.username}]];
var age = [[${user.age}]];
var username2 = "test username";
var user = [[${user}]];
</script>
<script>
var username = "UserA";
var age = 10;
var username2 = "UserA";
var user = {"username": "UserA", "age": 10};
</script>
자바스크립트 인라인 each를 사용한 경우
<script th:inline="javascript">
[# th:each="user, stat : ${users}"]
var user[[${stat.count}]] = [[${user}]];
[/]
</script>
<script>
var user1 = {"username": "UserA", "age": 10};
var user2 = {"username": "UserB", "age": 20};
var user3 = {"username": "UserC", "age": 30};
</script>
텍스트 렌더링
- 문자타입의 경우, 알아서
"
를 감싸준다.
- 또한 Escape 처리도 자동으로 해준다.
자바스크립트 Natural Template
- 주석을 활용해서, Natural Template 기능을 제공한다.
객체
Template 조각
- 웹페이지를 개발할 때는 공통 영역이 많다.
- Thymeleaf는 이런 문제를 해결하기 위해, Template Fragment와 Layout 기능을 지원한다.
th:fragment
를 통해 Template Fragment 를 정의한다.
th:insert
, th:replace
를 통해서 Template Fragment를 삽입하거나, 교체한다.
- insert는 현재 태그 내부에 추가
- replace는 현재 태그 대신 교체
- Template Fragment를 참조하는 문법은 아래와 같다.
~{template/fragment/{filename} :: }
- 하지만 생략 가능
th:fragment
<footer th:fragment="copy">
푸터 자리 입니다.
</footer>
th:insert
<div th:insert="~{template/fragment/footer :: copy}"></div>
<div th:insert="template/fragment/footer :: copy"></div>
<div>
<footer>
푸터 자리 입니다.
</footer>
</div>
th:replace
<div th:replace="~{template/fragment/footer :: copy}"></div>
<div th:replace="template/fragment/footer :: copy"></div>
<footer>
푸터 자리 입니다.
</footer>
파라미터 활용
<footer th:fragment="copyParam (param1, param2)">
<p>파라미터 자리 입니다.</p>
<p th:text="${param1}"></p>
<p th:text="${param2}"></p>
</footer>
<div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터2')}"></div>
<div th:replace="template/fragment/footer :: copyParam ('데이터1', '데이터2')"></div>
<footer>
<p>파라미터 자리 입니다.</p>
<p>데이터1</p>
<p>데이터2</p>
</footer>
Template Layout
Head 공통 부분
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="common_header(title,links)">
<title th:replace="${title}">레이아웃 타이틀</title>
<link rel="stylesheet" type="text/css" media="all" th:href="@{/css/awesomeapp.css}">
<link rel="shortcut icon" th:href="@{/images/favicon.ico}">
<script type="text/javascript" th:src="@{/sh/scripts/codebase.js}"></script>
<th:block th:replace="${links}" />
</head>
- ✅
common_header(~{::title},~{::link}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="template/layout/base :: common_header(~{::title},~{::link})">
<title>메인 타이틀</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">
</head>
<body>
메인 컨텐츠
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>메인 타이틀</title>
<link rel="stylesheet" type="text/css" media="all" href="/css/awesomeapp.css">
<link rel="shortcut icon" href="/images/favicon.ico">
<script type="text/javascript" src="/sh/scripts/codebase.js"></script>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/themes/smoothness/jquery-ui.css">
</head>
<body>
메인 컨텐츠
</body>
</html>
HTML 전체 레이아웃
<!DOCTYPE html>
<html th:fragment="layout (title, content)" xmlns:th="http://www.thymeleaf.org">
<head>
<title th:replace="${title}">레이아웃 타이틀</title>
</head>
<body>
<h1>레이아웃 H1</h1>
<div th:replace="${content}">
<p>레이아웃 컨텐츠</p>
</div>
<footer>
레이아웃 푸터
</footer>
</body>
</html>
<!DOCTYPE html>
<html th:replace="~{template/layoutExtend/layoutFile :: layout(~{::title}, ~{::section})}"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>메인 페이지 타이틀</title>
</head>
<body>
<section>
<p>메인 페이지 컨텐츠</p>
<div>메인 페이지 포함 내용</div>
</section>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>메인 페이지 타이틀</title>
</head>
<body>
<h1>레이아웃 H1</h1>
<section>
<p>메인 페이지 컨텐츠</p>
<div>메인 페이지 포함 내용</div>
</section>
<footer>
레이아웃 푸터
</footer>
</body>
</html>