HTML과의 자연스러운 통합
서버 사이드 렌더링
표준 HTML5 문법 사용
Thymeleaf에서 데이터를 표현하는 문법은 ${}
을 사용합니다.
<p th:text="${name}">이름</p>
th:text
속성은 컨트롤러에서 전달된 name 값을 화면에 출력합니다. 이름
은 Thymeleaf 문법이 동작하지 않는 경우에 보여질 기본 값입니다.th:with
변수를 선언하여 코드 중복을 줄일 수 있습니다.
<div th:with="welcomeMessage=${'Hello ' + name}">
<p th:text="${welcomeMessage}">Welcome</p>
</div>
th:with
를 사용해 welcomeMessage라는 변수에 값을 할당하고 사용합니다.th:each
th:each
를 사용하면 리스트나 배열을 반복해서 출력할 수 있습니다.
<ul>
<li th:each="user : ${userList}" th:text="${user.name}">사용자 이름</li>
</ul>
userList
는 컨트롤러에서 전달한 데이터입니다. user
는 반복 시 하나씩 꺼내 쓰는 변수입니다. ${user.name}
는 각 사용자 객체의 name
필드를 출력합니다.if
조건 - th:if
<p th:if="${age >= 18}" th:text="'성인입니다'">조건</p>
<p th:if="${age < 18}" th:text="'미성년자입니다'">조건</p>
unless
조건 - th:unless
<p th:unless="${age >= 18}" th:text="'미성년자입니다'">조건</p>
3항 연산자 사용
<p th:text="${age >= 18} ? '성인입니다' : '미성년자입니다'">조건</p>
th:href
링크를 동적으로 생성할 때 사용합니다.
<a th:href="@{/user/profile(id=${user.id})}">사용자 프로필</a>
@{}
문법은 링크를 동적으로 생성합니다. 다양한 HTML 속성에 값을 동적으로 할당할 수 있습니다.
<img th:src="@{/images/logo.png}" alt="로고" />
<input type="text" th:value="${username}" />
th:src
: 이미지 소스를 동적으로 설정합니다. th:value
: 입력 필드의 값을 설정합니다.th:insert
, th:replace
, th:include
를 사용하면 템플릿 일부를 재사용할 수 있습니다.
fragment 파일 (header.html):
<div th:fragment="header">
<h1>공통 헤더</h1>
</div>
재사용하는 파일:
<html>
<body>
<div th:replace="~{fragments/header :: header}"></div>
</body>
</html>
::
뒤에는 fragment의 이름을 지정합니다.Thymeleaf를 사용하면 JavaScript 코드에 서버 데이터를 쉽게 삽입할 수 있습니다.
<script th:inline="javascript">
var username = [[${username}]]; // 서버 데이터 삽입
console.log(username);
</script>
[[${}]]
는 JavaScript에 데이터를 삽입하는 표현식입니다.@Controller
public class UserController {
@GetMapping("/users")
public String getUsers(Model model) {
List<User> userList = Arrays.asList(new User("John"), new User("Jane"));
model.addAttribute("userList", userList);
return "userList";
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>사용자 목록</title>
</head>
<body>
<h1>사용자 목록</h1>
<ul>
<li th:each="user : ${userList}" th:text="${user.name}">사용자 이름</li>
</ul>
</body>
</html>
Thymeleaf는 HTML과의 자연스러운 통합과 직관적인 문법 덕분에 많은 개발자에게 사랑받는 템플릿 엔진입니다.
Spring Boot 프로젝트에서 Thymeleaf를 활용하면 빠르게 화면을 구현할 수 있습니다.
추가 학습 자료