2 분 소요

 인프런 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술편을 학습하고 정리한 내용 입니다.

반복

타임리프에서 반복은 th:each를 사용한다.

추가로 반복에서 사용할 수 있는 여러 상태 값을 지원한다.

BasicController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@GetMapping("/each")  
public String each(Model model) {  
    addUser(model);  
    return "basic/each";  
}  
  
private void addUser(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("user", list);  
}

resources/templates/basic/each.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>  
<html xmlns:th="http://www.thymeleaf.org">  
<head>  
  <meta charset="UTF-8">  
  <title>Title</title>  
</head>  
<body>  
<h1>기본 테이블</h1>  
<table border="1">  
  <tr>  
    <th>username</th>  
    <th>age</th>  
  </tr>  
  <tr th:each="user : ${users}">  
    <td th:text="${user.username}">username</td>  
    <td th:text="${user.age}">0</td>  
  </tr>  
</table>  
  
<h1>반복 상태 유지</h1>  
  
<table border="1">  
  <tr>  
    <th>count</th>  
    <th>username</th>  
    <th>age</th>  
    <th>etc</th>  
  </tr>  
  <tr th:each="user, userStat : ${users}">  
    <td th:text="${userStat.count}">username</td>  
    <td th:text="${user.username}">username</td>  
    <td th:text="${user.age}">0</td>  
    <td>  
      index = <span th:text="${userStat.index}"></span>  
      count = <span th:text="${userStat.count}"></span>  
      size = <span th:text="${userStat.size}"></span>  
      even? = <span th:text="${userStat.even}"></span>  
      odd? = <span th:text="${userStat.odd}"></span>  
      first? = <span th:text="${userStat.first}"></span>  
      last? = <span th:text="${userStat.last}"></span>  
      current = <span th:text="${userStat.current}"></span>  
    </td>  
  </tr>  
</table>  
  
  
</body>  
</html>

반복 기능

<tr th:each="user, userStat : ${users}">

  • 반복 시 오른쪽 컬렉션(${users})의 값을 하나씩 꺼내서 왼쪽 변수(user)에 담아서 태그를 반복 실행.
  • th:eachList뿐만 아니라 배열, java.util.Iterable, java.util.Enumeration을 구현한 모든 객체를 반복에 사용 가능. Map도 사용 가능한데, 이 경우 변수에 담기는 값은 Map.Entry

반복 상태 유지

<tr th:each="user, userStat : ${users}"> 반복의 두번째 파라미터를 설정해서 반복의 상태를 확인할 수 있다.

두번째 파라미터는 생략 가능한데, 생략하면 지정한 변수명(user) + Stat가 됨.

여기서는 user + Stat = userStat

반복 상태 유지 기능

  • index : 0부터 시작하는 값
  • count : 1부터 시작하는 값
  • size : 전체 사이즈
  • even , odd : 홀수, 짝수 여부( boolean )
  • first , last :처음, 마지막 여부( boolean )
  • current : 현재 객체

조건부 평가

타임리프의 조건 식

if, unless(if의 반대)

BasicController

1
2
3
4
5
@GetMapping("/condition")  
public String condition(Model model) {  
    addUser(model);  
    return "basic/condition";  
}

resources/templates/basic/condition.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE html>  
<html xmlns:th="http://www.thymeleaf.org">  
<head>  
    <meta charset="UTF-8">  
    <title>Title</title>  
</head>  
<body>  
<h1>if, unless</h1>  
<table border="1">  
    <tr>  
        <th>count</th>  
        <th>username</th>  
        <th>age</th>  
    </tr>  
    <tr th:each="user, userStat : ${users}">  
        <td th:text="${userStat.count}">1</td>  
        <td th:text="${user.username}">username</td>  
        <td>  
            <span th:text="${user.age}">0</span>  
            <span th:text="'미성년자'" th:if="${user.age lt 20}"></span>  
            <span th:text="'미성년자'" th:unless="${user.age ge 20}"></span>  
        </td>  
    </tr>  
</table>  
  
<h1>switch</h1>  
<table border="1">  
    <tr>  
        <th>count</th>  
        <th>username</th>  
        <th>age</th>  
    </tr>  
    <tr th:each="user, userStat : ${users}">  
        <td th:text="${userStat.count}">1</td>  
        <td th:text="${user.username}">username</td>  
        <td th:switch="${user.age}">  
            <span th:case="10">10살</span>  
            <span th:case="20">20살</span>  
            <span th:case="*">기타</span>  
        </td>  
    </tr>  
</table>  
  
</body>  
</html>

if, unless

타임리프는 해당 조건이 맞지 않으면 태그 자체를 렌더링 하지 않는다.

만약 다음 조건이 false인 경우

<span th:text="'미성년자'" th:if="${user.age lt 20}"></span>

이 태그 자체가 렌더링 안돼버린다.

switch

1
2
3
4
5
<td th:switch="${user.age}">  
	<span th:case="10">10살</span>  
	<span th:case="20">20살</span>  
	<span th:case="*">기타</span>  
</td>  

어렵진 않은데 * 이건 디폴트 값이다.

댓글남기기