[Thymeleaf] 조건부 평가(if, unless, switch)

Kade Jeon·2024년 2월 19일
0

Thymeleaf

목록 보기
12/22

조건식 활용

타임리프를 활용하여 Model로부터 넘어온 값의 조건에 따라 html 출력 여부를 지정할 수 있다. 아래 예제를 통해서 확인해볼 수 있다. 조건에 해당하지 않는 태그는 아예 렌더링하지 않는다.

<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>
  • users로 넘어오는 Model의 값(컬렉션)의 값에 따라서 반복문을 돌게 된다.
  • 반복문을 돌면서 컬렉션에서 객체를 하나씩 꺼내고, if 만약 나이가 20세 미만인 경우 미성년자가 출력된다.
  • unless의 경우, 영어와 같이 If not 으로 해석하면 정확히 같다. if의 반대개념
  • <th:if="${user.age lt 20}"> : 유저의 나이가 20미만이라면
  • <th:unless="${user.age ge 20}"> : 유저의 나이가 20 크거나 같지 않다면 -> 결국 20미만이라는 뜻.

switch 활용

Java와 유사하게 활용되며, 조건에 대한 결과 값 경우에 따라 태그를 처리할 수 있도록 한다. 이 또한 조건에 맞지 않는 case는 아예 렌더링이 되지 않는다.

<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>
  • <td th:switch="${user.age}"> : 객체에서 유저의 나이 값을 꺼내 case에 따라 활용한다.
  • * 의 경우, default 값으로 만족하는 case가 없을 경우 출력을 지정할 때 사용된다.
profile
안녕하세요. 백엔드 개발자가 되고 싶은 Kade 입니다.

0개의 댓글