웹 화면을 만들다 보면 특정 조건에 따라 데이터를 다르게 표시해야 하는 경우가 많다.
예를 들어 나이가 20세 미만이면 "미성년자"라고 표시하거나, 나이에 맞는 라벨을 붙여야 할 수 있다.
Thymeleaf는 이런 상황을 쉽게 처리할 수 있도록 th:if, th:unless, th:switch 같은 조건식 기능을 제공한다.
이번 글에서는 조건문을 어떻게 쓰는지, 그리고 결과가 어떻게 나오는지 살펴본다
1. 컨트롤러 코드
먼저 데이터를 뷰에 넘기기 위해 컨트롤러를 작성한다.
@GetMapping("/condition")
public String condition(Model model) {
addUsers(model);
return "basic/condition";
}
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);
}
여기서 users 리스트를 모델에 담아 화면에 전달한다.
2. 뷰 템플릿 예제
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>조건문 예제</title>
</head>
<body>
<h1>if, unless</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}">1</td>
<td th:text="${user.username}">username</td>
<td th:text="${user.age}">0</td>
<td>
<!-- if 조건 -->
<span th:text="'미성년자'" th:if="${user.age lt 20}"></span>
<!-- unless 조건 (if의 반대) -->
<span th:text="'성인'" th:unless="${user.age lt 20}"></span>
</td>
</tr>
</table>
<h1>switch</h1>
<table border="1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
<th>case</th>
</tr>
<tr th:each="user, userStat : ${users}">
<td th:text="${userStat.count}">1</td>
<td th:text="${user.username}">username</td>
<td th:text="${user.age}">0</td>
<td th:switch="${user.age}">
<span th:case="10">10살</span>
<span th:case="20">20살</span>
<span th:case="30">30살</span>
<span th:case="*">기타</span>
</td>
</tr>
</table>
</body>
</html>
3. 실행 결과

아래 switch 예제에서는 나이에 따라 10살, 20살, 30살, 기타 라벨이 출력된다.
th:case="*"는 default 역할을 한다.
4. 주요 특징
- if/unless
- th:if → 조건이 true일 때만 태그를 렌더링한다.
- th:unless → 조건이 false일 때만 태그를 렌더링한다.
- 조건이 맞지 않으면 태그 자체가 출력되지 않는다.
- switch/case
- Java의 switch문과 유사하다.
- th:switch에 지정된 값이 th:case와 일치하면 해당 태그를 출력한다.
- th:case="*"는 모든 조건에 해당하지 않을 때 실행되는 디폴트다.
마무리하며
Thymeleaf는 if, unless, switch 같은 조건식을 제공해서, 단순히 데이터를 보여주는 것뿐만 아니라 조건에 따라 다른 결과를 화면에 표시할 수 있도록 도와준다.
이 덕분에 개발자는 Java 코드에서 복잡한 분기 처리를 직접 HTML에 흩뿌리지 않아도 되고, 템플릿 단에서 깔끔하게 조건을 제어할 수 있다.
감사합니다.
'타임리프' 카테고리의 다른 글
| [Thymeleaf] 블록 (0) | 2025.09.16 |
|---|---|
| [Thymeleaf] 주석 (0) | 2025.09.16 |
| [Thymeleaf] 반복 (0) | 2025.09.16 |
| [Thymeleaf] 속성 값 설정 (0) | 2025.09.15 |
| [Thymeleaf] 연산 (0) | 2025.09.15 |
