BackEnd/Thymeleaf

타임리프 - 조건문

연향동큰손 2024. 7. 19. 19:59

 

타임리프에서 조건문을 구현 가능하다.

 

<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>

 

위 코드에서 user의 나이가 20살 미만, 이하면 미성년자를 출력하게 하는 기능을 if문을 통해 구현했다.

 

참고) 타임리프 비교,동등

- 비교 : >,<,>=,<=(gt,lt,ge,le)
- 동등 연산 : ==,!= ( eq,ne )

 

 

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

타임리프 - 템플릿 조각  (0) 2024.07.21
타임리프 - 블록  (0) 2024.07.19
타임리프-반복문  (0) 2024.07.19
타임리프-속성값 설정  (0) 2024.07.19
타임리프 - 리터럴  (0) 2024.07.16