본문 바로가기
Spring/Thymeleaf

th:each 예제

by YoonJong 2022. 9. 13.
728x90

반복문을 활용해서 List 에 값을 담아주었다.

 

 

@GetMapping("/ex03")
public String thymeleafExample03(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/thymeleafEx03";
}

 

th:each를 사용한다.

문법은 아래 예시와 같다.

th:each="item: ${itemDtoList}" 

item 을 사용해서 원하는 값을 나타낼 수 있다.

<!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:text="${status.index}"></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:if & th:unless 예제  (0) 2022.09.13
th:text 예제  (0) 2022.09.13
thymeleaf 소개, 시작해보기  (0) 2022.09.13

댓글