참고
더보기
Spring Boot & Thymeleaf 시리즈는 김영한 님의 "스프링 MVC 2편 - 백엔드 웹 개발 활용 기술" 강의를 정리한 글입니다. 글에 첨부된 사진은 해당 강의의 강의 자료에서 캡쳐한 것입니다. 제 Github에만 올려뒀다가, 정보 공유와 강의 홍보(?)를 위해 블로그에도 업로드합니다.
스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 - 인프런 | 강의
웹 애플리케이션 개발에 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. MVC 2편에서는 MVC 1편의 핵심 원리와 구조 위에 실무 웹 개발에 필요한 모든 활용 기술들을 학습할 수 있
www.inflearn.com
마크다운 형식으로 작성한 글을 블로그에 다시 올리는 거라 가독성이 많이 떨어집니다. 조금더 편하게 보시려면 아래의 Github repository에서 보시면 됩니다.
GitHub - Kloong1/TIL: Today I Learned.
Today I Learned. Contribute to Kloong1/TIL development by creating an account on GitHub.
github.com
타임리프 - if, unless, switch
타임리프는 조건식으로 if
와 unless
(if
의 반대)를 지원한다.
BasicController.java 내용 추가
package kloong.thymeleaf.basic;
import ... //생략
@Controller
@RequestMapping("/basic")
public class BasicController {
@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);
}
}
/resources/templates/basic/condition.html
<!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}">count</td>
<td th:text="${user.username}">username</td>
<td>
<span th:text="${user.age}">age</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}">count</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
if
는 조건식의 값이false
이면 태그 자체를 렌더링하지 않는다.<span th:text="'미성년자'" th:if="${user.age lt 20}"></span>
- 만약
user.age
가 20 미만인 경우 위 태그 전체가 렌더링 되지 않고 사라진다.
unless
는if
의 반대이다. 조건식의 값이true
이면 태그 자체를 렌더링하지 않는다.<span th:text="'미성년자'" th:unless="${user.age ge 20}"></span>
- 만약
user.age
가 20 이상인 경우 위 태그 전체가 렌더링 되지 않고 사라진다.
switch
- case
- Java의 Switch-case와 동일하다.
*
은default
를 의미한다.if
,unless
와 마찬가지로 조건을 만족하는case
외의 태그는 전부 렌더링되지 않고 사라진다.
참고
th:if="${user.age lt 20}"
이렇게도 되고,th:if="${user.age} lt 20"
이렇게도 된다.
'Spring > Spring Boot & Thymeleaf' 카테고리의 다른 글
[Spring Boot & Thymeleaf] 13. Block 태그 (0) | 2022.10.24 |
---|---|
[Spring Boot & Thymeleaf] 12. 주석 (0) | 2022.10.24 |
[Spring Boot & Thymeleaf] 10. 반복 (0) | 2022.10.24 |
[Spring Boot & Thymeleaf] 9. 타임리프 - 속성 값 설정 (0) | 2022.10.24 |
[Spring Boot & Thymeleaf] 8. 연산/연산자 (0) | 2022.10.24 |
댓글