본문 바로가기
Spring/Thymeleaf

th:if & th:unless 예제

by YoonJong 2022. 9. 13.
728x90
@GetMapping("/ex04")
public String thymeleafExample04(Model model) {
    List<ItemDto> itemDtoList = new ArrayList<>();

    for (int i = 1; i <= 10; i++) {
        ItemDto itemDto = new ItemDto();
        itemDto.setItemNm("테스트 상품" + i);
        itemDto.setItemDetail("상품 상세 설명" + i);
        itemDto.setPrice(i*10000);
        itemDto.setRegTime(LocalDateTime.now());

        itemDtoList.add(itemDto);
    }
    model.addAttribute("itemDtoList", itemDtoList);
    return "thymeleafEx/thymeleafEx04";
}

 

 짝수일때는 짝수 를 출력하고

 짝수가 아닐때는 홀수를 출력하는 예제이다.

<td th:if="${status.even}" th:text="짝수"></td>
<td th:unless="${status.even}" th:text="홀수"></td>

 

 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>상품 리스트 출력 예제</h1>

    <table border="1">
        <thead>
            <tr>
            <td>순번</td>
            <td>상품명</td>
            <td>상품설명</td>
            <td>가격</td>
            <td>상품등록일</td>
            </tr>
        </thead>
        <tbody th:each="item, status : ${itemDtoList}">
            <td th:if="${status.even}" th:text="짝수"></td>
            <td th:unless="${status.even}" th:text="홀수"></td>
            <td th:text="${item.itemNm}"></td>
            <td th:text="${item.itemDetail}"></td>
            <td th:text="${item.price}"></td>
            <td th:text="${item.regTime}"></td>
        </tbody>
    </table>
</body>
</html>

 

결과

728x90

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

th:href 예제  (0) 2022.09.13
th:switch & th:case 예제  (0) 2022.09.13
th:each 예제  (0) 2022.09.13
th:text 예제  (0) 2022.09.13
thymeleaf 소개, 시작해보기  (0) 2022.09.13

댓글