타임리프의 기본 기능에 대해 알아보자.
우선 그 전에 프로젝트를 하나 생성한다. 생성은 아래와 같이 생성해준다.

Dependency는 Spring Web, Lombok, Thymeleaf를 적용하였다.
타임리프
타임리프의 공식 사이트 및 메뉴얼은 다음과 같다.
타임리프 특징
- 서버 사이드 HTML 렌더링(SSR)
- 네츄럴 템플릿
- 스프링 통합 지원
서버 사이드 HTML 렌더링(SSR)
타임리프는 백엔드 서버에서 HTML을 동적으로 렌더링하는 용도로 사용된다.
네츄럴 템플릿
타임리프는 순수 HTML을 최대한 유지하는 특징이 있다.
타임리프로 작성한 파일은 HTML을 유지하기 때문에 웹 브라우저에서 파일을 직접 열어도 내용을 확인할 수 있고, 서버를 통해 뷰 템플릿을 거치면 동적으로 변경된 결과를 확인할 수 있다.
JSP를 포함한 다른 뷰 템플릿들은 해당 파일을 열면, 예를 들어 JSP 파일 자체를 그대로 웹 브라우저에서 열어보면, JSP 소스코드와 HTML이 뒤죽박죽 섞여서 웹 브라우저에서 정상적인 HTML 결과를 확인할 수 없다. 오직 서버를 통해서 JSP가 렌더링되고 HTML 응답 결과를 받아야 화면을 확인할 수 있다.
반면에 타임리프로 작성된 파일은 해당 파일을 그대로 웹 브라우저에서 열어도 정상적인 HTML 결과를 확인할 수 있다. 물론 이 경우 동적으로 결과가 렌더링 되지는 않는다. 하지만 HTML 마크업 결과가 어떻게 되는지 파일만 열어도 바로 확인할 수 있다.
이렇게 순수 HTML을 그대로 유지하면서 뷰 템플릿도 사용할 수 있는 타임리프의 특징을 네츄럴 템플릿이라 한다.
스프링 통합 지원 : 타임리프는 스프링과 자연스럽게 통합되고, 스프링의 다양한 기능을 편리하게 사용할 수 있게 지원한다.
텍스트 - text, utext
타임리프의 가장 기본 기능인 텍스트를 출력하는 기능 먼저 알아보자.
타임리프는 기본적으로 HTML 태그의 속성에 기능을 정의해서 동작한다. HTML의 콘텐츠(content)에 데이터를 출력할때는 다음과 같이 th:text를 사용하면 된다.
<span th:Ptext="${data}">
HTML 태그의 속성이 아니라 HTML 콘텐츠 영역 안에서 직접 데이터를 출력하고 싶으면 다음과 같이 [[...]]를 사용하면 된다.
컨텐츠 안에서 직접 출력하기 = [[${data}]]
BasicController를 생성해보자.
@Controller
@RequestMapping("/basic")
public class BasicController {
@GetMapping("/text-basic")
public String textBasic(Model model) {
model.addAttribute("data", "Hello <b>Spring</b>");
return "basic/text-basic";
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>컨텐츠에 데이터 출력하기</h1>
<ul>
<li>th:text 사용 <span th:text="${data}"></span></li>
<li>컨텐츠 안에서 직접 출력하기 = [[${data}]]</li>
</ul>
</body>
</html>
th:text는 태그 내부의 기존 내용을 대체하게 되고
[[...]]는 내부의 표현식이 해당 위치에서 직접 치환된다.
Escape
HTML문서는 <,>같은 특수 문자를 기반으로 정의된다. 따라서 뷰 템플릿으로 HTML 화면을 생성할때는 출력하는 데이터에 특수문자가 있는 것을 주의해서 사용해야 한다.
만약 Hello Spring를 <b>태그를 사용해서 진하게 만들고 싶다고 가정하자.
"Hello <b>Spring</b>"
@GetMapping("/text-basic")
public String textBasic(Model model) {
model.addAttribute("data", "Hello <b>Spring</b>");
return "basic/text-basic";
}
하지만 웹 브라우저를 확인해보면 우리의 의도와는 다른 결과가 나타나는 것을 볼 수 있는데

페이지의 소스를 확인해보면 다음과 같다.
<li>th:text 사용 <span>Hello <b>Spring</b></span></li>
<li>컨텐츠 안에서 직접 출력하기 = Hello <b>Spring</b></li>
우리의 원래 의도는 Spring을 강조하도록 하는 것이였으나, <b> 태그가 그대로 출력되는 것을 볼 수 있다.
소스를 보면 < 부분이 <로 변경된 것 또한 관찰할 수 있다.
HTML엔티티
웹 브라우저는 <를 HTML 태그의 시작으로 인식한다. 따라서 <를 태그의 시작이 아니라 문자로 표현할 수 있는 방법이 필요한데, 이것을 HTML 엔티티라고 한다. 그리고 이렇게 HTML에서 사용하는 특수 문자를 HTML 엔티티로 변경하는 것을 이스케이프(escape)라고 한다. 그리고 타임리프가 제공하는 th:text, [[...]]는 기본적으로 이스케이프를 제공한다.
Unescape
이스케이프 기능을 사용하지 않으려면 어떻게 해야할까?
--> 타임 리프는 다음 두 기능을 제공한다.
th:text -> th:utext 로 변경
[[...]] -> [(...)] 로 변경
@GetMapping("/text-unescaped")
public String textUnescaped(Model model) {
model.addAttribute("data", "Hello <b>Spring</b>");
return "basic/text-unescaped";
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<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>
</body>
</html>
* th:inline="none" : 타임리프는 [[...]]를 해석하기 때문에, 화면에 [[...]] 글자를 보여줄 수 없다. 따라서 이 태그 안에서는 타임리프가 해석하지 말라는 옵션을 주자.

실행해보면 우리의 의도대로 결과가 나오는 것을 확인할 수 있다.
주의 : 실제 서비스를 개발하다 보면, escape를 사용하지 않아서 HTML이 정상 렌더링 되지 않는 수 많은 문제가 발생한다. escape를 기본으로 하고, 꼭 필요할때만 unescape를 사용하자.
변수 - SpringEL
타임리프에서 변수를 사용할 떄는 변수 표현식을 사용한다.
SpringEL은 Spring에서 사용하는 표현식 언어로, 객체의 속성 값 접근, 연산, 조건문, 메서드 호출 등을 가능하게 한다.
Thymeleaf등 여러곳에서 활용된다.
변수 표현식 : ${...}
그리고 이 변수 표현식에는 스프링 EL이라는 스프링이 제공하는 표현식을 사용할 수 있다.
우선 BasicController에 다음을 추가해보자.
@GetMapping("/variable")
public String variable(Model model) {
User userA = new User("userA", 10);
User userB = new User("userB", 20);
List<User> list = new ArrayList<>();
list.add(userA);
list.add(userB);
Map<String, User> map = new HashMap<>();
map.put("userA", userA);
map.put("userB", userB);
model.addAttribute("user", userA);
model.addAttribute("users", list);
model.addAttribute("userMap", map);
return "basic/variable";
}
@Data
static class User {
private String username;
private int age;
public User(String username, int age) {
this.username = username;
this.age = age;
}
}
return "basic/variable"이므로 basic디렉토리 하위에 variable.html을 만들어주자.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>SpringEL 표현식</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>${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>
<h1>지역 변수 - (th:with)</h1>
<div th:with="first=${users[0]}">
<p>처음 사람의 이름은 <span th:text="${first.username}"></span></p>
</div>
</body>
</html>
타임리프를 활용하여 만들어진 html을 확인해보자.

SpringEL을 활용하여 다양한 표현식이 사용되었다.
Object
1. user.username : user의 username을 프로퍼티 접근하였다. -> user.getUsername()
2. user['username'] : 위와 동일하다. -> user.getUsername()
3. user.getUsername() : user의 getUsername()을 직접 호출하였다.
List
1. users[0].username : List에서 첫번째 회원을 찾고 username 프로퍼티 접근을 하였다. -> list.get(0).getUsername()
2. users[0]['username'] : 위와 동일하다.
3. users[0].getUsername() : List에서 첫번째 회원을 찾고 메서드를 직접 호출하였다.
Map
1. userMap['userA'].username : Map에서 userA를 찾고, username 프로퍼티 접근을 하였다. -> map.get("userA").getUsername()
2. userMap['userA']['username'] : 위와 동일하다.
3. userMap['userA'].getUsername() : Map에서 userA를 찾고 메서드를 직접 호출하였다.
타임리프는 지역 변수를 선언해서 사용할수도 있다.
th:with을 사용하면 지역 변수를 선언하여 사용한다는 뜻이다. 지역 변수는 선언한 태그 안에서만 사용할 수 있다.
<h1>지역 변수 - (th:with)</h1>
<div th:with="first=${users[0]}">
<p>처음 사람의 이름은 <span th:text="${first.username}"></span></p>
</div>
위 코드는 변수 이름이 first로 선언된 것이다.
유틸리티 객체와 날짜
타임리프는 문자, 숫자, 날짜 URI등을 편리하게 다루는 다양한 유틸리티 객체들을 제공한다.
*타임리프 유틸리티 객체들
- #message : 메시지, 국제화 처리
- #uris : URI 이스케이프 지원
- #dates : java.util.Date 서식지원
- #calendars : java.Calendar 서식 지원
- #temporals : 자바8 날짜 서식 지원
- #numbers : 숫자 서식 지원
- #strings : 문자 관련 편의 기능
- #objects : 객체 관련 기능 제공
- #bools : boolean 관련 기능 제공
- #arrays : 배열 관련 기능 제공
- #lists, #sets, #maps : 컬렉션 관련 기능 제공
- #ids : 아이디 처리 관련 기능 제공
참고 : 이런 유틸리티 객체들은 대략 이런 것이 있다 정도로만 알아두고, 필요할때마다 찾아서 사용하면 된다.
자바8 날짜 : 타임리프에서 자바8 날짜인 LocalDate, LocalDateTime, Instant를 사용하려면 추가 라이브러리가 필요하다. 스프링 부트 타임리프를 사용하면 해당 라이브러리가 자동으로 추가되고 통합된다.
타임리프 자바8 날짜 지원 라이브러리
thymeleaf-extras-java8time
참고 : 스프링 부트 3.2 이상을 사용한다면, 타임리프 자바8 날짜 지원 라이브러리가 이미 포함되어 있기 때문에 별도로 포함하지 않아도 된다.
자바8날짜용 유틸리티 객체 : #temporals
날짜를 한번 확인해보자.
@GetMapping("/date")
public String date(Model model) {
model.addAttribute("localDateTime", LocalDateTime.now());
return "basic/date";
}
date.html을 만들자.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<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>
<h1>LocalDateTime - Utils</h1>
<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></body>
</html>

위와 같은 결과를 확인할 수 있다.
yyyy-MM-dd HH:mm:ss로 포매팅된 결과도 확인할 수 있다.
URL 링크
타임리프에서 URL을 생성할때는 @{...} 문법을 사용하면 된다.
@GetMapping("/link")
public String link(Model model) {
model.addAttribute("param1", "data1");
model.addAttribute("param2", "data2");
return "basic/link";
}
link.html을 생성해보자.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>URL 링크</h1>
<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>
</body>
</html>
단순한 URL
- @{/hello} -> /hello
쿼리 파라미터
- @{/hello(param1=${param1}, param2=${param2})}
-> /hello?param1=data1¶m2=data2
-> ()에 있는 부분이 쿼리 파라미터로 처리된다.
경로 변수
- @{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}
-> /hello/data1/data2
-> URL 경로상에 변수가 있으면 ()부분은 경로 변수로 처리된다.
경로 변수 + 쿼리 파라미터
- @{/hello/{param1}(param1=${param1, param2=${param2})}
-> /hello/data1?param2=data2
-> 경로 변수와 쿼리 파라미터를 함께 사용할 수 있다.
상대 경로, 절대 경로, 프로토콜 기준을 표현할 수도 있다.
- /hello : 절대 경로
- hello : 상대 경로
리터럴(Literals)
리터럴은 소스 코드 상에 고정된 값을 말하는 용어이다.
예를 들어 다음 코드에서는 "Hello"가 문자 리터럴 10, 20은 숫자 리터럴이다.
String a = "hello";
int a = 10 * 20
**참고 : 이 내용은 쉬워 보이지만 처음 타임리프를 사용하면 실수를 많이 하니 잘 보도록 하자.
타임리프는 다음과 같은 리터럴이 있다.
- 문자 : 'hello'
- 숫자 : 10
- 불린 : true, false
- null : null
타임리프에서 문자 리터럴은 항상 '(작은따음표)로 감싸야 한다.
<span th:text=" 'hello' ">
그러나 문자를 항상 '(작은따옴표)로 감싸는 것은 너무 귀찮은 일이다. 공백 없이 쭉 이어진다면, 하나의 의미있는 토큰으로 인지해서 다음과 같이 작은 따옴표를 생략할 수 있다.(룰은 아래와 같다)
룰 : A-Z, a-z, 0-9, [], ., -, _
<span th:text="hello">
오류
<span th:text="hello world!"></span>
문자 리터럴은 원칙상 ' 로 감싸야 한다. 중간에 공백이 있어서 하나의 의미있는 토큰으로 인식되지 않는다
수정
<span th:text=" 'hello world!' "></span>
이렇게 ' 로 감싸면 정상 동작한다.
예제를 통해서 확인해보자.
@GetMapping("/literal")
public String literal(Model model) {
model.addAttribute("data", "Spring!");
return "basic/literal";
}
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<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>
</body>
</html>
리터럴 대체(Literal substitutions)
<span th:text="|hello ${data}|">
마지막의 리터럴 대체 문법을 사용하면 마치 템플릿을 사용하는 것처럼 편리하다.
연산
타임리프 연산은 자바와 크게 다르지 않다. HTML안에서 사용하기 때문에 HTML 엔티티를 사용하는 부분만 주의하자.
@GetMapping("/operation")
public String operation(Model model) {
model.addAttribute("nullData", null);
model.addAttribute("data", "Spring!");
return "basic/operation";
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<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>
</body>
</html>
컨트롤러 및 HTML의 결과는 다음과 같다.

- 비교연산 : HTML 엔티티를 사용해야 하는 부분을 주의하자.
- >(gt), <(lt), >=(ge), <=(le), !(not), ==(eq), !=(neq, ne)
- 조건식 : 자바의 조건식과 유사하다.
- Elvis : 조건식의 편의 버전이다. 현재 addAttribute로 data에는 Spring! 이 nullData에는 null이 넘겨졌다.
- No-Operation : _ 인 경우 마치 타임리프가 실행되지 않는 것 처럼 동작한다. 이것을 잘 사용하면 HTML의 내용 그대로 활용할 수 있다. 마지막 예를 보면 데이터가 없습니다. 부분이 그대로 출력되는것을 확인할 수 있다.
속성 값 설정
타임리프 태그 속성(Attribute)
타임리프는 주로 HTML 태그에 th:* 속성을 지정하는 방식으로 동작한다. th:*로 속성을 적용하면 기존 속성을 대체한다. 기존 속성이 없으면 새로 만든다.
Basic Controller와 attribute.html을 추가해보자.
@GetMapping("/attribute")
public String attribute() {
return "basic/attribute";
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title></head>
<body>
<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" /><br/>
<h1>checked 처리</h1>
- checked o <input type="checkbox" name="active" th:checked="true" /><br/>
- checked x <input type="checkbox" name="active" th:checked="false" /><br/>
- checked=false <input type="checkbox" name="active" checked="false" /><br/>
</body>
</html>
결과는 다음과 같다.

<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Title</title></head> | |
<body> | |
<h1>속성 설정</h1> | |
<input type="text" name="userA" /> | |
<h1>속성 추가</h1> | |
- th:attrappend = <input type="text" class="textlarge" /><br/> | |
- th:attrprepend = <input type="text" class="largetext" /><br/> | |
- th:classappend = <input type="text" class="text large" /><br/> | |
<h1>checked 처리</h1> | |
- checked o <input type="checkbox" name="active" checked="checked" /><br/> | |
- checked x <input type="checkbox" name="active" /><br/> | |
- checked=false <input type="checkbox" name="active" checked="false" /><br/> | |
</body> | |
</html> |
속성 설정
th:* 속성을 지정하면 타임리프는 기존 속성을 th:*로 지정한 속성으로 대체한다. 기존 속성이 없다면 새로 만든다.
<input type="text" name="mock" th:name="userA" />
-> 타임리프 렌더링 후 <input type="text" name="userA" />
속성 추가
th:attrappend :속성 값의 뒤에 값을 추가한다.
th:attrprepend : 속성 값의 앞에 값을 추가한다.
th:classappend : class 속성에 자연스럽게 추가한다.
checked 처리
HTML에서는 <input type="checkbox" name="active" checked="false" /> -> 이 경우도 checked 속성이 있기 때문에 checked 처리가 되어버린다.
HTML에서 checked 속성은 checked 속성의 값과 상관없이 checked 라는 속성만 있어도 체크가 된다. 이런 부분이 true, false 값을 주로 사용하는 개발자 입장에서는 불편한다.
타임리프의 th:checked는 값이 false인 경우 checked 속성 자체를 제거한다.
<input type="checkbox" name="active" th:checked="false" />
--> 타임리프 렌더링 후 : <input type="checkbox" name="active" />
반복
타임리프에서 반속은 th:each를 사용한다. 추가로 반복에서 사용할 수 있는 여러 상태 값을 지원한다.
@GetMapping("/each")
public String each(Model model) {
addUsers(model);
return "basic/each";
}
private void addUsers(Model model) {
List<User> list = new ArrayList<>();
list.add(new User("userA", 10));
list.add(new User("userB", 20));
list.add(new User("userC", 30));
model.addAttribute("users", list);
}
다음과 같은 코드를 추가하고, each.html을 만들자.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>기본 테이블</h1>
<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>
<h1>반복 상태 유지</h1>
<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>
</body>
</html>
위 코드의 결과는 다음과 같다.

반복 기능
<tr th:each="user : ${users}">
- 반복시 오른쪽 컬렉션(${users})의 값을 하나씩 꺼내서 왼쪽 변수(user)에 담아 태그를 반복 실행한다.
- th:each는 List뿐만 아니라 배열, java.util.Iterable, java.util.Enumeration을 구현한 모든 객체를 반복에 사용할 수 있다.
Map도 사용할 수 있는데 이 경우 변수에 담기는 값은 Map.Entry이다.
반복 상태 유지
<tr th:each="user, userStat : ${users}">
반복의 두번째 파라미터를 설정해서 반복의 상태를 확인할 수 있다.
두번쨰 파라미터는 생략 가능한데, 생략하면 지정한 변수명(user) + Stat이 된다.
여기서는 user + stat = userStat이므로 생략 가능하다.
반복 상태 유지 기능
- index : 0부터 시작하는 값
- count : 1부터 시작하는 값
- size : 전체 사이즈
- even, odd : 홀수, 짝수 여부(boolean)
- first, last : 처음, 마지막 여부(boolean)
- current : 현재 객체
조건부 평가
타임리프의 조건식은 총 두가지이다
1. if
2. unless(if의 반대)
@GetMapping("/condition")
public String condition(Model model) {
addUsers(model);
return "basic/condition";
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head><body>
<h1>if, unless</h1>
<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>
<h1>switch</h1>
<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>
</body>
</html>

if, unless
타임리프는 해당 조건이 맞지 않으면 태그 자체를 렌더링하지 않는다.
만약 다음 조건이 false인 경우 <span>...</span> 부분 자체가 렌더링 되지 않고 사라진다.
switch
*은 만족하는 조건이 없을때 사용되는 디폴트이다.
주석
주석은 종류가 여러가지이다. 우선 확인해보자.
@GetMapping("/comments")
public String comments(Model model) {
model.addAttribute("data", "Spring!");
return "basic/comments";
}
<!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>
<!--
<span th:text="${data}">html data</span>
-->
<h1>2. 타임리프 파서 주석</h1>
<!--/* [[${data}]] */-->
<!--/*-->
<span th:text="${data}">html data</span>
<!--*/--><h1>3. 타임리프 프로토타입 주석</h1>
<!--/*/
<span th:text="${data}">html data</span>
/*/-->
</body>
</html>
결과를 확인해보자.

<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Title</title> | |
</head> | |
<body> | |
<h1>예시</h1> | |
<span>Spring!</span> | |
<h1>1. 표준 HTML 주석</h1> | |
<!-- | |
<span th:text="${data}">html data</span> | |
--> | |
<h1>2. 타임리프 파서 주석</h1> | |
<h1>3. 타임리프 프로토타입 주석</h1> | |
<span>Spring!</span> | |
</body> | |
</html> |
1. 표준 HTML 주석
자바 스크립트의 표준 HTML 주석은 타임리프가 렌더링하지 않고, 그대로 남겨둔다.
2. 타임리프 파서 주석
타임리프 파서 주석은 타임리프의 진짜 주석이다. 렌더링에서 주석 부분을 제거한다.
3. 타임리프 프로토타입 주석
타임리프 프로토타입은 약간 특이한데, HTML 주석에 약간의 구문을 더했다.
HTML 파일을 웹 브라우저에서 그대로 열어보면 HTML 주석이기 때문에 이 부분이 웹 브라우저가 렌더링하지 않는다.
타임리프 렌더링을 거치면 이 부분이 정상 렌더링 된다.
쉽게 이야기해서 HTML 파일을 그대로 열어보면 주석처리가 되지만, 타임리프를 렌더링 한 경우에만 보이는 기능이다.
블록
<th:block>은 HTML 태그가 아닌 타임리프의 유일한 자체 태그다.
@GetMapping("/block")
public String block(Model model) {
addUsers(model);
return "basic/block";
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<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>
</body>
</html>
타임리프의 특성상 HTML 태그 안에 속성으로 기능을 정의해서 사용하는데, 위 예처럼 이렇게 사용하기 애매한 경우에 사용하면 된다. <th:block>은 렌더링 시 제거된다.
자바스크립트 인라인
타임리프는 자바스크립트에서 타임리프를 편리하게 사용할 수 있는 자바스크립트 인라인 기능을 제공한다.
자바스크립트 인라인 기능은 다음과 같이 적용하면 된다.
@GetMapping("/javascript")
public String javascript(Model model) {
model.addAttribute("user", new User("userA", 10));
addUsers(model);
return "basic/javascript";
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head> <meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- 자바스크립트 인라인 사용 전 -->
<script>
var username = [[${user.username}]];
var age = [[${user.age}]];
//자바스크립트 내추럴 템플릿
var username2 = /*[[${user.username}]]*/ "test username";
//객체
var user = [[${user}]];
</script>
<!-- 자바스크립트 인라인 사용 후 -->
<script th:inline="javascript">
var username = [[${user.username}]];
var age = [[${user.age}]];
//자바스크립트 내추럴 템플릿
var username2 = /*[[${user.username}]]*/ "test username";
//객체
var user = [[${user}]];
</script>
</body>
</html>
템플릿 조각
웹 페이지를 개발할때는 공통 영역이 많이 있다. 예를 들어 상단 영역이나 하단 영역, 좌측 카테고리 등등 여러 페이지에서 함께 사용하는 영역들이 있다. 이런 부분을 코드를 복사해서 사용한다면 변경시 여러 페이지를 다 수정해야 하므로 상당히 비효율적이다. 타임리프는 이런 문제를 해결하기 위해 템플릿 조각과 레이아웃 기능을 지원한다.
우선 컨트롤러를 만들어보자.
@Controller
@RequestMapping("/template")
public class TemplateController {
@GetMapping("/fragment")
public String template() {
return "/template/fragment/fragmentMain";
}
}
fragmentMain HTML은 footer를 활용하여 만들어진 템플릿이다.
그렇기 때문에 footer를 먼저 만들어주어야 한다.
경로는 다음과 같다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<footer th:fragment="copy">
푸터 자리 입니다.
</footer>
<footer th:fragment="copyParam (param1, param2)">
<p>파라미터 자리 입니다.</p>
<p th:text="${param1}"></p>
<p th:text="${param2}"></p>
</footer>
</body>
</html>
th:fragment가 있는 태그는 다른 곳에 포함되는 코드 조각으로 이해하면 된다.
이제 이 footer를 활용한 fragmentMain을 확인해보자.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<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>
</body>
</html>
위 코드의 결과는 다음과 같다.

<!DOCTYPE html> |
<html> |
<head> |
<meta charset="UTF-8"> |
<title>Title</title> |
</head> |
<body> |
<h1>부분 포함</h1> |
<h2>부분 포함 insert</h2> |
<div><footer> |
푸터 자리 입니다. |
</footer></div> |
<h2>부분 포함 replace</h2> |
<footer> |
푸터 자리 입니다. |
</footer> |
<h2>부분 포함 단순 표현식</h2> |
<footer> |
푸터 자리 입니다. |
</footer> |
<h1>파라미터 사용</h1> |
<footer> |
<p>파라미터 자리 입니다.</p> |
<p>데이터1</p> |
<p>데이터2</p> |
</footer> |
</body> |
</html> |
- template/fragment/footer :: copy 는 template/fragment/footer.html 템플릿에 있는 th:fragment="copy"라는 부분을 템플릿 조각으로 가져와서 사용한다는 의미이다.
copy의 부분은 다음과 같다.
<footer th:fragment="copy">
푸터 자리 입니다.
</footer>
부분 포함 insert
<div th:insert="~{template/fragment/footer :: copy}"></div>
<h2>부분 포함 insert</h2> <div> <footer> 푸터 자리 입니다. </footer> </div> |
th:insert를 사용하면 현재 태그(div) 내부에 추가한다.
부분 포함 replace
<div th:replace="~{template/fragment/footer :: copy}"></div>
<h2>부분 포함 replace</h2> <footer> 푸터 자리 입니다. </footer> |
th:replace를 사용하면 현재 태그(div)를 대체한다.
부분 포함 단순 표현식
<div th:replace="template/fragment/footer :: copy"></div>
<h2>부분 포함 단순 표현식</h2> <footer> 푸터 자리 입니다. </footer> |
원래 위 replace처럼 ~{...}를 사용하는 것이 원칙이지만, 템플릿 조각을 사용하는 코드가 단순하면 이 부분을 생략할 수 있다.
파라미터 사용
다음과 같이 파라미터를 전달해서 동적으로 조각을 렌더링할수도 있다.
<div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터2')}"></div>
<h1>파라미터 사용</h1> <footer> <p>파라미터 자리 입니다.</p> <p>데이터1</p> <p>데이터2</p> </footer> |
<footer th:fragment="copyParam (param1, param2)">
<p>파라미터 자리 입니다.</p>
<p th:text="${param1}"></p>
<p th:text="${param2}"></p>
</footer>
템플릿 레이아웃1
이전에는 일부 코드 조각을 가지고와서 사용했다면, 이번에는 개념을 더 확장해서 코드 조각을 레이아웃에 넘겨서 사용하는 방법에 대해 알아보자.
예를 들어'<head>'에 공통으로 사용하는 'css', 'javascript'같은 정보들이 있는데, 이러한 공통 정보들을 한곳에 모아두고, 공통으로 사용하지만, 각 페이지마다 필요한 정보를 더 추가해서 사용하고 싶다면, 다음과 같이 사용하면 된다.
@GetMapping("/layout")
public String layout() {
return "/template/layout/layoutMain";
}
<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>
<!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>
-common_header(~{::title}, ~{::link}) 이 부분이 핵심이다.
- ::title은 현재 페이지의 title 태그들을 전달한다.
- ::link는 현재 페이지의 link태그들을 전달한다.
결과를 확인해보자.
<!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> |
- 메인 타이틀이 전달한 부분으로 교체되었다.
- 공통 부분은 그대로 유지되고, 추가 부분에 전달한 <link>들이 포함된 것을 확인할 수 있다.
이 방식은 앞서 배운 코드 조각을 조금 더 적극적으로 사용하는 방식이다. 쉽게 이야기해서 레이아웃 개념을 두고, 그 레이아웃에 필요한 코드 조각을 전달해서 완성하는 것이다.
템플릿 레이아웃2
템플릿 레이아웃 확장
앞서 이야기한 개념을 <head> 정도에만 적용하는게 아니라 <html> 전체에 적용할 수도 있다.
@GetMapping("/layoutExtend")
public String layoutExtend() {
return "/template/layoutExtend/layoutExtendMain";
}
<!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> |
layoutFile.html을 보면 기본 레이아웃을 가지고 있는데, <html>에 th:fragment 속성이 정의되어 있다. 이 레이아웃 파일을 기본으로 하고, 여기에 필요한 내용을 전달해서 부분부분 변경하는 것으로 이해하면 된다.
layoutExtendMain.html은 현재 페이지인데, <html> 자체를 th:replace를 사용해서 볁경하는 것을 확인할 수 있다. 결국 loayoutFile에 대한 필요한 내용을 전달하면서 <html> 자체를 layoutFile.html로 변경한다.
'공부 > Spring' 카테고리의 다른 글
메시지, 국제화 (0) | 2025.03.30 |
---|---|
타임리프 - 스프링 통합과 폼 (0) | 2025.03.29 |
스프링 MVC 웹 페이지 만들기 (0) | 2025.03.25 |
스프링 MVC - 기본 기능 (0) | 2025.03.20 |
스프링 MVC - 구조 이해 (0) | 2025.03.17 |