2 분 소요


반복

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

BasicController

@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);
}

<!-- 기본 -->
<tr th:each="user : ${users}">
    <td th:text="${user.username}">username</td>
    <td th:text="${user.age}">0</td>
</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>

반복 기능
<tr th:each="user : ${users}">

  • 반복시 오른쪽 컬렉션(${users})의 값을 하나씩 꺼내서 왼쪽 변수(user)에 담아서 태그를 반복 실행.
  • th:eachMap도 사용할 수 있는데, 이 경우 변수에 담기는 값은 Map.Entry이다.

반복 상태 유지
<tr th:each="user, userStat : ${users}">

  • 반복의 두 번째 파라미터를 설정해서 반복의 상태를 확인할 수 있다.
  • 두 번째 파라미터는 생략 가능한데, 생략하면 지정한 변수명(user) + Stat이 된다.

반복 상태 유지 기능

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


조건부 평가

타임리프의 조건식
if, unless(if의 반대)

BasicController

@GetMapping("/condition")
public String condition(Model model) {
    addUsers(model);    //list에 userA, userB, userC
    return "basic/condition";
}

<!-- if, unless -->
<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>

<!-- switch -->
<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>

출력 결과
if

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

  • 타임리프는 해당 조건이 맞지 않으면 태그 자체를 렌더링하지 않는다.
    • 만약 다음 조건이 false인 경우 <span>...</span>부분 자체가 렌더링되지 않고, 사라진다.

switch
*은 만족하는 조건이 없을 때 사용하는 디폴트이다.(else)


주석

BasicController

@GetMapping("/comments")
public String comments(Model model) {
    model.addAttribute("data", "Spring!");
    return "basic/comments";
}

<!-- 1. 표준 HTML 주석 -->

<!--
<span th:text="${data}">html data</span>
-->

<!-- 2. 타임리프 파서 주석 -->

<!--/* [[${data}]] */-->

<!--/*-->
<span th:text="${data}">html data</span>
<!--*/-->

<!-- 3. 타임리프 프로토타입 주석 -->

<!--/*/
<span th:text="${data}">html data</span>
/*/-->

결과

타임리프 렌더링
comment1

HTML 파일
comment2

1. 표준 HTML 주석
자바스크립트의 표준 HTML 주석은 타임리프가 렌더링 하지 않고, 그대로 남겨둔다.

2. 타임리프 파서 주석
타임리프 파서 주석은 타임리프의 진짜 주석이다. 렌더링에서 주석 부분을 제거.

3. 타임리프 프로토타입 주석(잘 사용X)

  • HTML 파일을 웹 브라우저에서 그대로 열어보면 HTML 주석이기 때문에 웹 브라우저가 렌더링하지 않는다.
  • 타임리프 렌더링을 거치면 이 부분이 정상 렌더링 된다.
  • 결론: HTML파일을 그대로 열어보면 주석처리가 되지만, 타임리프를 렌더링 한 경우에는 보이는 기능이다.


블록

<th:block>은 HTML 태그가 아닌 타임리프의 유일한 자체 태그.

BasicController

@GetMapping("/block")
public String block(Model model) {
    addUsers(model);
    return "basic/block";
}

<th:block th:each="user : ${users}">
    <div>
        사용자 이름1 <span th:text="${user.username}"></span>
        사용자 나이1 <span th:text="${user.age}"></span>
    </div>

    <div>
        요약 <span th:text="${user.username} + ' / ' + ${user.age}"></span>
    </div>
</th:block>

결과
block

타임리프의 특성상 HTML 태그 속성으로 기능을 정의해서 사용하지만, 위 예시처럼 사용하기 애매한 경우에 사용하면 된다.<th:block>은 렌더링시 제거된다.


<출처 : 인프런 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술(김영한)>

댓글남기기