스프링 MVC 2편(백엔드 웹 개발 활용 기술)

Ch01. 타임리프(기본 기능) - 반복

webmaster 2022. 3. 10. 10:47
728x90
@GetMapping("/each")
public String each(Model model){
    addUsers(model);
    return "basic/each";
}

private void addUsers(Model model){
    List<User> list = new ArrayList<>();
    list.add(new User("userA", 10));
    list.add(new User("userB", 20));
    list.add(new User("userC", 30));
    model.addAttribute("users", list);
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h1>속성 설정</h1>
<input type="text" name="mock" th:name="userA" />
<h1>속성 추가</h1>
- th:attrappend = <input type="text" class="text" th:attrappend="class=' large'" /><br/>
- th:attrprepend = <input type="text" class="text" th:attrprepend="class='large '" /><br/>
- th:classappend = <input type="text" class="text" th:classappend=" large" /><br/>
<h1>checked 처리</h1>
- checked o <input type="checkbox" name="active" th:checked="true" /><br/>
- checked x <input type="checkbox" name="active" th:checked="false" /><br/>
- checked=false <input type="checkbox" name="active" checked="false" /><br/>
</body>
</html>
  • 반복 기능
    • <tr th:each="user : ${users}">
    • 반복 시 오른쪽 컬렉션( ${users} )의 값을 하나씩 꺼내서 왼쪽 변수( user )에 담아서 태그를 반복 실행합니다.
    • th:each 는 List 뿐만 아니라 배열, java.util.Iterable , java.util.Enumeration을 구현한 모든 객체를 반복에 사용할 수 있습니다. Map 도 사용할 수 있는데 이 경우 변수에 담기는 값은 Map.Entry입니다.
  • 반복 상태 유지
    • 반복의 두 번째 파라미터를 설정해서 반복의 상태를 확인 할 수 있습니다.
    • <tr th:each="user, userStat : ${users}">
    • 두번째 파라미터는 생략 가능한데, 생략하면 지정한 변수명( user ) + Stat 가 됩니다.
      • index : 0부터 시작하는 값
      • count : 1부터 시작하는 값
      • size : 전체 사이즈
      • even , odd : 홀수, 짝수 여부( boolean )
      • first , last :처음, 마지막 여부( boolean )
      • current : 현재 객체
728x90