Thymeleaf를 사용하기 위해 프로젝트 세팅 시 thymeleaf를 미리 설정해두면 사용하기 편하다.
#thymeleaf cache
spring.thymeleaf.cache=false
를 입력하여 파일 저장 시 thymeleaf가 바로 적용 될 수 있도록 해준다.<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
</head>
<body>
</body>
</html>
html파일의 html 태그에 xmlns:th="http://www.thymeleaf.org"을 추가
.thymeleaf.thymeleaf 패키지 생성
...
<a href="/basic/text-basic">텍스트 기본 출력</a>
...
@Controller
@RequestMapping("/basic") // 기본 URL
public class BasicController {
@GetMapping("text-basic")// ' / ' 생략 가능
public String textBasic(Model model) {
model.addAttribute("data", "Hello!");
return "basic/text-basic";
}
}
<h1>컨텐츠 데이터 출력하기</h1>
<ul>
<li>th:text 사용 = <span th:text="${data}"></span> </li>
<li>컨텐츠 안에서 직접 출력하기 = [[${data}]]</li>
</ul>
출력
...
<a href="/basic/text-unescaped">텍스트 text, utext</a>
...
...
@GetMapping("text-unescaped")
public String textUnescaped(Model model) {
model.addAttribute("data", "<b>Hello!!</b>");
return "basic/text-unescaped";
}
}
<h1>text vs utext</h1>
<ul>
<li>th:text = <span th:text="${data}"></span> </li>
<li>th:utext = <span th:utext="${data}"></span> </li>
</ul>
<h1>
<span th:inline="none">[[...]] vs [(...)]</span>
</h1>
<ul>
<li><span th:inline="none">[[...]] = </span>[[${data}]]</li>
<li><span th:inline="none">[(...)] = </span>[(${data})]</li>
</ul>
출력
thymeleaf > data 패키지 생성
@Getter @Setter
public class User {
private String username;
private int age;
public User(String username, int age) {
super();
this.username = username;
this.age = age;
}
}
...
<a href="/basic/variable">변수</a>
...
...
@GetMapping("variable")
public String variable(Model model) {
User userA = new User("UserA", 10);
User userB = new User("UserB", 20);
List<User> list = new ArrayList<User>();
list.add(userA);
list.add(userB);
Map<String, User> map = new HashMap<String, User>();
map.put("UserA", userA);
map.put("UserB", userB);
model.addAttribute("user", userA);
model.addAttribute("userList", list);
model.addAttribute("userMap", map);
return "basic/variable";
}
}
<h1>표현식</h1>
<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>
${userList[0].username} = <span th:text="${userList[0].username}"></span>
</li>
<li>
${userList[0]['username']} = <span th:text="${userList[0]['username']}"></span>
</li>
<li>
${userList[0].getUsername()} = <span th:text="${userList[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>
<hr>
<h1>지역변수 - (th:with)</h1>
<div th:with="first=${userList[0]}">
<p>
처음 사람의 이름은 <span th:text="${first.username}"></span>
</p>
</div>
출력
thymeleaf > bean 패키지 생성
@Component("helloBean")
public class HelloBean {
public String hello(String data) {
return "Hello" + data;
}
}
...
<a href="/basic/basic-objects?paramData=paramValue">기본객체들</a>
...
...
@GetMapping("basic-objects")
public String basicObjects(HttpSession session ) {
session.setAttribute("sessionData", "sessionValue");
return "basic/basic-objects";
}
}
<h1>기본 객체</h1>
<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>
<!-- /basic/basic-objects?paramData=paramValue -->
<hr>
<h1>편의 객체</h1>
<ul>
<li>Request Parameter = <span th:text="${#httpServletRequest.getParameter('paramData')}"></span></li>
<li>Request Parameter2 = <span th:text="${#request.getParameter('paramData')}"></span></li>
<li>Request Parameter3 = <span th:text="${param.paramData}"></span></li>
<hr>
세션
<li>session = <span th:text="${session.sessionData}"></span></li>
<hr>
<li>spring bean = <span th:text="${@helloBean.hello('user!')}"></span> </li>
</ul>
출력
...
<a href="/basic/date">유틸리티 객체와 날짜</a>
...
...
@GetMapping("date")
public String date(Model model) {
model.addAttribute("localDateTime", LocalDateTime.now());
return "basic/date";
}
}
<h1>LocalDateTime</h1>
<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>
<hr>
<h1>LocalDateTime</h1>
<ul>
<li>${#temporals.day(localDateTime)} = <span th:text="${#temporals.day(localDateTime)}"></span> </li>
</ul>
<ul>
<li>${#temporals.month(localDateTime)} = <span th:text="${#temporals.month(localDateTime)}"></span> </li>
</ul>
<ul>
<li>${#temporals.monthName(localDateTime)} = <span th:text="${#temporals.monthName(localDateTime)}"></span> </li>
</ul>
<ul>
<li>${#temporals.year(localDateTime)} = <span th:text="${#temporals.year(localDateTime)}"></span> </li>
</ul>
<ul>
<li>${#temporals.dayOfWeek(localDateTime)} = <span th:text="${#temporals.dayOfWeek(localDateTime)}"></span> </li>
</ul>
<ul>
<li>${#temporals.dayOfWeekName(localDateTime)} = <span th:text="${#temporals.dayOfWeekName(localDateTime)}"></span> </li>
</ul>
<ul>
<li>${#temporals.hour(localDateTime)} = <span th:text="${#temporals.hour(localDateTime)}"></span> </li>
</ul>
<ul>
<li>${#temporals.minute(localDateTime)} = <span th:text="${#temporals.minute(localDateTime)}"></span> </li>
</ul>
<ul>
<li>${#temporals.second(localDateTime)} = <span th:text="${#temporals.second(localDateTime)}"></span> </li>
</ul>
출력
...
<a href="/basic/link">링크 URL</a>
...
...
@GetMapping("link")
public String link(Model model) {
model.addAttribute("param1", "data1");
model.addAttribute("param2", "data2");
return "basic/link";
}
}
<h1>URL 링크</h1>
<ul>
<li>
<a th:href="@{/hello}">basic url</a>
</li>
<li>
<a th:href="@{/hello(param1=${param1},param2=${param2})}">param url</a>
</li>
<li>
<a th:href="@{/hello/{param1}/{param2}(param1=${param1},param2=${param2})}">path url</a>
</li>
<li>
<a th:href="@{/hello/{param1}(param1=${param1},param2=${param2})}">param + path url</a>
</li>
</ul>
출력
<span th:text="'hello'">
<span th:text="hello">
<span th:text="hello world!">
(오류)<span th:text="'hello world!'">
...
<a href="/basic/literal">literal</a>
...
...
@GetMapping("literal")
public String literal(Model model) {
model.addAttribute("data", "spring");
return "basic/literal";
}
}
<h1>리터럴</h1>
<ul>
<!-- <li> "hello world!" = <span th:text="hello world!"></span></li> -->
<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>
출력
(gt/>), <(lt), >=(ge), <=(le), !(not), ==(eq), !=(neq, ne)
...
<a href="/basic/operation">연산</a>
...
...
@GetMapping("operation")
public String operation(Model model) {
model.addAttribute("data", "spring");
model.addAttribute("nullData", null);
return "basic/operation";
}
}
<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 == 10 = <span th:text="1 == 10"></span> </li>
<li> 1 != 10 = <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>
출력
...
<a href="/basic/attribute">속성 값 설정</a>
...
...
@GetMapping("attribute")
public String attribute(Model model) {
return "basic/attribute";
}
}
<h1>속성 설정</h1>
<input type="text" name="mock" th:name="userA">
<h1>속성 추가</h1>
- th:attrappend = <input type="text" class="text" th:attrappend="class='large'">
<br>
- th:attrprepend = <input type="text" class="text" th:attrprepend="class='large'">
<br>
- th:classappend = <input type="text" class="text" th:classappend="large">
<h1>checked 처리</h1>
- checked = false = <input type="checkbox" name="active" checked="false">
<br>
- checked x = <input type="checkbox" name="active" th:checked="false">
<br>
- checked o = <input type="checkbox" name="active" th:checked="true">
<br>
출력
...
<a href="/basic/each">반복</a>
...
...
@GetMapping("each")
public String each(Model model) {
addUser(model);
return "basic/each";
}
private void addUser(Model model) {
List<User> list = new ArrayList<User>();
list.add(new User("userA", 10));
list.add(new User("userB", 20));
list.add(new User("userC", 30));
model.addAttribute("userList",list);
}
}
<h1>반복문</h1>
<table border="1">
<tr>
<th>username</th>
<th>age</th>
</tr>
<tr th:each=" user : ${userList} ">
<td th:text="${user.username}">username</td>
<td th:text="${user.age}">0</td>
</tr>
</table>
<hr>
<h1>반복 상태 유지</h1>
<table border="1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
<th>etc</th>
</tr>
<tr th:each=" user, userStat : ${userList} ">
<td th:text="${userStat.count}">
<td th:text="${user.username}">username</td>
<td th:text="${user.age}">0</td>
<td>index = <span th:text="${userStat.index}"></span> </td>
<td>count = <span th:text="${userStat.count}"></span> </td>
<td>size = <span th:text="${userStat.size}"></span> </td>
<td>even = <span th:text="${userStat.even}"></span> </td>
<td>odd = <span th:text="${userStat.odd}"></span> </td>
<td>first = <span th:text="${userStat.first}"></span> </td>
<td>last = <span th:text="${userStat.last}"></span> </td>
<td>current = <span th:text="${userStat.current}"></span> </td>
</tr>
</table>
출력
...
<a href="/basic/condition">조건부 평가</a>
...
...
@GetMapping("condition")
public String condition(Model model) {
addUser(model);
return "basic/condition";
}
}
<h1>if, unless</h1>
<table border="1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
</tr>
<tr th:each=" user : ${userList} ">
<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>
<hr>
<table border="1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
</tr>
<tr th:each=" user : ${userList} ">
<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>
출력
...
<a href="/basic/comments">주석</a>
...
...
@GetMapping("comments")
public String comments(Model model) {
model.addAttribute("data", "spring");
return "basic/comments";
}
}
<h1>예시</h1>
<span th:text="${data}">html data</span>
<h1>1. 표준 HTML 주석</h1>
<!-- <span th:text="${data}">html data</span> -->
<h1>2. 타임리프 주석</h1>
<!--/* [[${data}]] */-->
<!--/* -->
<span th:text="${data}">html data</span>
<!-- */-->
출력
...
<a href="/basic/block">블록</a>
...
...
@GetMapping("block")
public String block(Model model) {
addUser(model);
return "basic/block";
}
}
<th:block th:each="user : ${userList}">
<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>
출력
...
<a href="/basic/javascript">자바스크립트</a>
...
...
@GetMapping("javascript")
public String javascript(Model model) {
model.addAttribute("user", new User("UserD", 10));
addUser(model);
return "basic/javascript";
}
}
<!-- 자바스크립트 인라인 사용 전 -->
<script>
let username = "[[${user.username}]]";
let age = [[${user.age}]];
//객체
// let user = [[${user}]];
</script>
<!-- 자바스크립트 인라인 사용 후 -->
<script th:inline="javascript">
let username2 = [[${user.username}]];
let age2 = [[${user.age}]];
//객체
let user = [[${user}]];
</script>
<!-- 자바스크립트 인라인 each -->
<script th:inline="javascript">
[# th:each = "user, stat:${userList}"]
let user[[${stat.count}]]=[[${user}]];
[/]
</script>
출력
<a href="/template/fragment">템플릿 조각</a>
@Controller
@RequestMapping("template")
public class TemplateController {
@GetMapping("fragment")
public String fragment() {
return "template/fragment/fragmentMain";
}
}
<footer th:fragment="copy">
footer 자리입니다.
</footer>
<footer th:fragment="copyParam(param1, param2)">
<p>파라미터 자리입니다.</p>
<p th:text="${param1}"></p>
<p th:text="${param2}"></p>
</footer>
<h1>부분포함</h1>
<h2>부분포함 insert</h2>
<div th:insert="~{template/fragment/footer :: copy}"></div>
<h2>부분포함 replace</h2>
<div th:replace="~{template/fragment/footer :: copy}"></div>
<h2>부분포함 단순 표현식</h2>
<div th:replace="template/fragment/footer :: copy"></div>
<h1>파라미터 사용</h1>
<div th:replace="~{template/fragment/footer :: copyParam('데이터1','데이터2')}"></div>
출력
<a href="/template/layout">유연한 layout</a>
...
@GetMapping("layout")
public String layout() {
return "template/layout/layoutMain";
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<!-- 전체 사이트에서 가져다 쓰는 공통 layout -->
<head th:fragment="common_header(title,links)">
<meta charset="UTF-8">
<title th:replace="${title}">레이아웃 타이틀</title>
<!-- 공통 -->
<link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.css}">
<script type="text/javascript" th:src="@{/sh/script/base.js}"></script>
<!-- 추가 -->
<th:block th:replace="${links}"/>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="template/layout/base :: common_header(~{::{title}, ~{::links})">
<meta charset="UTF-8">
<title>메인 타이틀</title>
<link rel="stylesheet" th:href="@{/css/chart.min.css}">
<link rel="stylesheet" th:href="@{/themes/jquery.min.css}">
</head>
<body>
메인 컨텐츠
</body>
</html>
출력