※ 인프런 김영한님 강의를 본인의 이해를 바탕으로 작성한 글이므로 사용법에 틀린 부분이 존재할 수 있습니다.
- 서버사이드 HTML 렌더링
- 네츄럴 템플릿
- 스프링 통합 지원
<html xmlns:th="http://www.thymeleaf.org">
ex) <span th:text="${data}"></span>
ex) <span>[[${data}]]</span>
<!-- ex) Object -->
${user.username} / ${user['username']} / ${user.getUsername()}
<!-- ex) List -->
${users[0].username} / ${users[0]['username']} / ${users[0].getUsername()}
<!-- ex) Map -->
${userMap['userA'].username} / ${user['userA']['username']} / ${user['userA'].getUsername()}
<div th:with="first=${users[0]}"></div>
<input th:text=${#request} />
<input th:text=${#response} />
<input th:text=${#session} />
<input th:text=${#servletContext} />
<input th:text=${#locale} />
<!-- 결과 : 해당 객체의 주소값이 나옴 -->
<!-- model 값 접근 -->
<input th:text="${#param.paramData}" />
<!-- session 값 접근 -->
<input th:text="${#session.sessionData}" />
<!-- bean으로 등록된 값에 직접 접근 -->
<input th:text="${@helloBean.hello('Spring!')}" />
-> 해당 객체의 데이터 값이 나옴
<link th:href="@{/hello}" >
<link th:href="@{/hello(param1=${param1}, param2=${param2})}" >
<link th:href="@{/hello/{param1}}" >
<link th:href="@{/hello/{param1}}/param1=${param1}, param2=${param2})" >
<input th:text="'hello' + ' world!'" />
<input th:text="'hello world!'" />
<input th:text="'hello ' + ${data}" />
<input th:text="|hello ${data}|" />
<span th:text = "${data}?: _">데이터가 없습니다.</span>
<!-- 데이터가 없을 경우 text가 그대로 출력 -->
속성을 지정하면 타임리프는 기존 속성을 th:로 대체
ex)
<input type="text" name="user" th:name="thUser" />
속성 추가
-> 띄워쓰기가 중요
<input class="normal" th:attrappend="class=' append'" />
<!-- class="normal" 에서 class="normal large"로 추가 -->
<input class="normal" th:attrprepend="class='large '" />
<!-- class="normal" 에서 class="large normal"로 추가 -->
<input class="normal" th:classappend="class=' large'" />
<!-- class="text" 에서 class="text large"로 추가 -->
checked 처리
<input type="checkbox" name="check" th:checked="true" />
<input type="checkbox" name="check" th:checked="false" />
<input type="checkbox" name="check" checked="false" />
th:each
ex)
<tr th:each="user : ${users}">
<td th:text="${user.username}"></td>
<td th:text="${user.age}"></td>
</tr>
배열, Iterable, Enumeration, Map까지 사용 가능
-> Map의 경우 변수에 담기는 값은 Map.Entry
반복 상태
<tr th:each="user, userStatus : ${users}">
-> 두번째 파라미터 설정을 통해 상태확인 가능
<tr th:text="${userStatus.index}">
<tr th:text="${userStatus.count}">
<tr th:text="${userStatus.size}">
<tr th:text="${userStatus.even}"> <!-- boolean -->
<tr th:text="${userStatus.odd}"> <!-- boolean -->
<tr th:text="${userStatus.first}"> <!-- boolean -->
<tr th:text="${userStatus.last}"> <!-- boolean -->
<tr th:text="${userStatus.current}"> <!-- 현재 값 -->
-> 두번째 파라미터는 생략가능하며 생략 시 변수 + Stat을 활용
<!-- -->
<!--/* */--> <!-- 한줄 -->
<!--/* --> <!-- */--> <!-- 범위 -->
-> 렌더링 시 해당 부분 제거<!--/*/ /*/-->
-> 타임리프로 렌더링 된 경우에만 표시 <th:block th:each="user : ${users}"></th:block>
<th:block th:each="user : ${users}">
<div>${user.name}</div>
<div>${user.age}</div>
</th:block>
<script th:inline="javascript">
// model 접근
var username = "[[${user.username}]]";
// 자바스크립트 내추럴 템플릿
var username = /*[[${user.username}]]*/;
// 객체
var user = [[${user}]];
// => toString()의 형태로 전달 ex) Controller.User(키=값)
// model 접근
var username = [[${user.username}]];
// 자바스크립트 내추럴 템플릿
var username = /*[[${user.username}]]*/;
// 객체
var user = [[${user}]];
[# th:each="user, stat : ${users}"]
var user[[${stat.count}]] = [[${user}]]
[/]
<footer th:fragment="copy"></footer>
<footer th:fragment="copyParam (param1, param2)">
<p th:text="${param1}"></p>
<p th:text="${param2}"></p>
</footer>
<!-- 포함 : div가 유지 -->
<div th:insert="~{template/fragment/footer :: copy}">
<!-- 부분 포함 : div를 footer로 대체 -->
<div th:replace="~{template/fragment/footer :: copy}">
<!-- 부분 포함 단순 표현식 -->
<div th:replace="template/fragment/footer :: copy">
<!-- 파라미터 사용 : 해당 값을 형식에 맞춰 렌더링 -->
<div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터2')}">
공통으로 사용하는 정보들을 레이아웃에 넘겨 적용
기본
-> 선언
<head th:fragment="commmonHeader(title, links)">
<title th:replace="${title}">레이아웃 타이틀</title>
<!-- 공통 -->
<link>
<script></script>
<!-- 추가 -->
<th:block th:replace="${links}" />
</head>
-> 적용
<head th:replace="template/layout/base :: common_header(~{::title}, ~{::link})">
<title>개별 타이틀</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}" />
</head>
확장
-> 선언
<html th:fragment="layout (title, content)" xmlns:th="http://www.thymeleaf.org">
<head th:fragment="commmonHeader(title, links)">
<title th:replace="${title}">레이아웃 타이틀</title>
</head>
<body>
<h1>레이아웃 H1</h1>
<div th:replace="${content}">
<p>레이아웃 컨텐츠</p>
</div>
<footer>
레이아웃 푸터
</footer>
</body>
</html>
-> 적용
<html th:replace="~{template/layoutExtend/layoutFile :: layout(~{::title}, ~{::section})}"
xmlns:th="http//www.thymeleaf.org">
출처 : [스프링 MVC 2편 - 백엔드 웹 개발 활용 기술](인프런)