Java/Thymeleaf

조건부 평가

코딩공부 2021. 12. 3. 00:52

조건부 평가

타임리프의 조건식 if , 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

count username age
1 userA 10 미성년자 미성년자
2 userB 20
3 userC 30

 

switch

count username age
1 userA 10살
2 userB 20살
3 userC 기타

 

if, unless

타임리프는 해당 조건이 맞지 않으면 태그 자체를 렌더링하지 않는다.

만약 다음 조건이 false 인 경우 <span>...</span> 부분 자체가 렌더링 되지 않고 사라진다.

렌더링 전 - <span th:text="'미성년자'" th:if="${user.age lt 20}"></span> 

렌더링 후 - 

if 조건 결과가 false 일 경우  렌더링 되지 않음

 

switch

* 은 만족하는 조건이 없을 때 사용하는 디폴트이다.

 

 

수강 강의

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-2/dashboard

 

스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 - 인프런 | 강의

웹 애플리케이션 개발에 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. MVC 2편에서는 MVC 1편의 핵심 원리와 구조 위에 실무 웹 개발에 필요한 모든 활용 기술들을 학습할 수 있

www.inflearn.com

 

'Java > Thymeleaf' 카테고리의 다른 글

블록  (0) 2021.12.10
주석  (0) 2021.12.03
반복  (0) 2021.12.03
속성 값 설정  (0) 2021.12.03
연산  (0) 2021.12.03