본문 바로가기
Spring/Thymeleaf

th:switch & th:case 예제

by YoonJong 2022. 9. 13.
728x90
@GetMapping("/ex05")
public String thymeleafExample05(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";
}

 

여러개의 조건을 처리해야할 때 사용한다.

switch 문에 들어간 조건에 따라 출력하는 값을 정한다.

짝수가 true 일때는 짝수,

짝수가 false 일때는 홀수를 출력한다.

<td th:switch="${status.even}">
    <span th:case="true">짝수</span>
    <span th:case="false">홀수</span>
</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:switch="${status.even}">
                <span th:case="true">짝수</span>
                <span th:case="false">홀수</span>
            </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' 카테고리의 다른 글

Thymeleaf 페이지 레이아웃  (0) 2022.09.14
th:href 예제  (0) 2022.09.13
th:if & th:unless 예제  (0) 2022.09.13
th:each 예제  (0) 2022.09.13
th:text 예제  (0) 2022.09.13

댓글