Thymeleaf

th:each 예제

쿠카이든 2022. 2. 15. 14:10
728x90
@GetMapping(value = "/ex03")
public String thymeleafExample03(Model model){

    List<ItemDto> itemDtoList = new ArrayList<>();

    for(int i=1;i<=10;i++){

        ItemDto itemDto = new ItemDto();
        itemDto.setItemDetail("상품 상세 설명"+i);
        itemDto.setItemNm("테스트 상품" + i);
        itemDto.setPrice(1000*i);
        itemDto.setRegTime(LocalDateTime.now());

        itemDtoList.add(itemDto);
    }

    model.addAttribute("itemDtoList", itemDtoList);
    return "thymeleafEx/thymeleafEx03";
}
  • 반복문을 통해 화면에서 출력할 10개의 itemDto 객체를 만들어서 itemDtoList에 넣는다.
  • 화면에서 출력할 itemDtoList를 model에 담아서 View에 전달한다.
<table border="1">
    <thead>
    <tr>
        <td>순번</td>
        <td>상품명</td>
        <td>상품설명</td>
        <td>가격</td>
        <td>상품등록일</td>
    </tr>
    </thead>
    <tbody>
    <tr th:each="itemDto, status: ${itemDtoList}">
        <td th:text="${status.index}"></td>
        <td th:text="${itemDto.itemNm}"></td>
        <td th:text="${itemDto.itemDetail}"></td>
        <td th:text="${itemDto.price}"></td>
        <td th:text="${itemDto.regTime}"></td>
    </tr>
    </tbody>
</table>
  • th:each를 이용하면 자바의 for문처럼 반복문을 사용할 수 있다.
    • 전달받은 itemDtoList에 있는 데이터를 하나씩 꺼내와서 itemDto에 담아줍니다.
    • status에는 현재 반복에 대한 상태 데이터가 존재합니다.
  • status.index -> 현재 순회하고 있는 데이터의 인덱스를 출력합니다.

localhost/thymeleaf/ex03 페이지의 결과

 

출처: 스프링부트 쇼핑몰 프로젝트 with JPA

728x90

'Thymeleaf' 카테고리의 다른 글

SpringEL  (0) 2023.03.18
th:switch, th:case 예제  (0) 2022.02.15
th:text DTO 활용 예제  (0) 2022.02.14
(Thymeleaf) th:text  (0) 2022.02.14