티스토리 뷰

반응형

타임리프의 조건식에 대해 살펴보겠다

타임리프가 제공하는 조건식은 대략 아래와 같다

• if : 자바의 if와 같음 해당 값이 맞으면 true 아니면 false

• unless : if의 반대

• switch : 자바의 switch와 같이 맞는 case가 있으면 치환한다

 

Simple Conditionals : if & unless

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

즉 아래의 if 혹은 unless의 결과가 false가 나올 시 해당 <span> 태그 자체가 렌더링 되지 않고 사라진다

<!-- Simple Conditionals (if & unless) -->
(생략)
<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}">userCount</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>
(생략)

 

Switch Statements

자바의 Switch문처럼 해당 case값이 있으면 그 값이 렌더링되며 이외에 값들은 사라진다

아무런 값지 맞지 않을 경우를 대비하여 * 로 디폴트 값을 설정할 수 있다

<!-- Switch -->
(생략)
<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>
(생략)

 

더보기

개인 학습을 위해 작성되는 글입니다.

제가 잘못 알고 있는 점에 대한 지적 / 더 나은 방향에 대한 댓글을 환영합니다.

 

참조 링크:

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

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

 

반응형

'WEB > Template Engine' 카테고리의 다른 글

[Thymeleaf] Block tag (블록 태그)  (0) 2021.09.02
[Thymeleaf] Comments (주석)  (0) 2021.09.02
[Thymeleaf] Object Binding (객체 바인딩)  (0) 2021.09.01
[Thymeleaf] Iteration (반복)  (0) 2021.09.01
[Thymeleaf] Attribute (속성)  (0) 2021.09.01
댓글