Notice
Recent Posts
Recent Comments
Link
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

[Thymeleaf] 조건 부 평가, if, unless, switch, case 본문

인프런/[인프런] 스프링 MVC 2

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

Seung__ 2021. 9. 19. 00:08

1. Thymeleaf의 조건식


  • if 
  • unless ( if 의 반대)

 

2. if, unless


  • 타임리프는 해당 조건이 맞지 않으면 태그 자체를 렌더링하지 않는다.
  • 만약 다음 조건이 false 인 경우 <span>...<span> 부분 자체가 렌더링 되지 않고 사라진다.
  • <span th:text="'미성년자'" th:if="${user.age lt 20}"></span>
    • user.age가 10인경우 if문이 true -> th:text="미성년자" 랜더링됨.

 

 

3. switch


  • * 은 만족하는 조건이 없을 때 사용하는 디폴트 값.
  • <td th:switch="${user.age}">
    <span th:case="10">10살</span>
    <span th:case="20">20살</span>
    <span th:case="*">기타</span>
    </td>

 

 

4. Controller


    @GetMapping("/condition")
    public String condition(Model model){
        addUsers(model);
        return "basic/condition";
    }

 

 

5. 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}">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>

 

6. GitHub : 210918 Condition


 

GitHub - bsh6463/Thymeleaf

Contribute to bsh6463/Thymeleaf development by creating an account on GitHub.

github.com

 

'인프런 > [인프런] 스프링 MVC 2' 카테고리의 다른 글

[Thymeleaf] block, <ht:block>  (0) 2021.09.19
[Thymeleaf] 주석  (0) 2021.09.19
[Thymeleaf] 반복, each  (0) 2021.09.18
[Thymeleaf] 속성 값 설정  (0) 2021.09.18
[Thymeleaf] 연산  (0) 2021.09.18
Comments