[Thymeleaf] 타임리프 기본 기능 2 - 속성 값 설정, 반복, 조건부 평가, 주석, 블록

2025. 6. 28. 17:35·Spring/Thymeleaf

이전 글에 이어 타임리프의 속성 값, 반복, 조건부 평가, 주석 및 블록에 대해 알아보자


흐름을 따라가기 위한 컨트롤러

package hello.thymeleaf.basic;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.Data;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

    @GetMapping("/attribute")
    public String attribute() {
        return "basic/attribute";
    }

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

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

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

   


    @Data
    static class User {
        private String username;
        private int age;

        public User(String username, int age) {
            this.username = username;
            this.age = age;
        }
    }
}

속성 값 설정

타임리프는 주로 HTML 태그에 th:* 속성을 지정하는 방식으로 동작한다.

뭔소리냐면, 기존의 디폴트 값이 있을 때 타임리프로 렌더링시, th:* 의 속성을 통해 해당 값을 치환하는 식으로 작동한다는 의미이다.

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

속성 설정에서, name이 mock으로 기본 설정이 되어 있을 때, 파일 경로로 HTML을 열게 되면 이름이 mock으로 출력된다.

하지만 한번 타임리프를 통해 렌더링 되면 name 이라는 필드가 userA로 치환 되게 된다.

 

속성 추가

append는 기본적으로 이어 붙이다는 의미이다.

"대상 속성=' 이어 붙일 내용'" 이라는 수식을 통해 앞 뒤 등등에 이어붙인다.

attrappend는 속성 값 뒤에 이어붙이게 되고, attrprepend는 속상 값 앞에 이어붙이게 된다.

추가로 classappend는 편의기능인데, class 속성에 자연스럽게 추가해주는 편의 기능이다.

 

편리한 checked 설정

원래 HTML에선 checked 라는 필드의 값이 true든 false든 알빠노 하고 필드의 존재유무에 따라 체크 박스를 체크해버린다.(싸가지ㅋㅋ)

타임리프의 th:checked 를 통해 우리가 자바코딩 하듯이 boolean값을 할당할 수 있게 된다.

그래서 만약 th:checked 값이 false라면 속성 자체를 제거해버린다 (HTML에서는 속성 자체가 없으면 체크가 안된걸로 판단하기 때문)


반복

바아아아로 코드로 고고링

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

자바의 for-each문의 형태와 유사하다.

th:each="사용할 변수 : ${가져온 컬렉션}" 형태로 선언하고, 사용할 변수.필드 를 통해 값을 사용할 수 있다.

또한 타임리프는 반복에 대한 상태도 표현할 수 있는데, 두번째 변수로 변수명 + Stat 을 설정하여 반복에 대한 세부정보를 확인할 수 있다.

index, count, size 등등 확인 가능함 ~


조건부 평가

타임리프의 조건식은 대표적으로 if, unless 가 있다.

if: 만약 ~ 라면 참일 때 실행, 거짓일 때 실행X

unless : ~이 아니라면 참일 때 실행 X, 거짓일 때 실행

<!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}">1</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>

간단하게 해당 HTML을 설명하자면, 먼저 표의 행을 만든다(count, username, age)

이후 반복을 돌리는데, 코드 순서대로 행의 한 칸에 데이터를 추가한다.

user의 나이를 넣고(디폴트 text는 0 인데 타임리프로 인해 치환),

user의 이름을 가져온뒤, 3번째 <td> 태그안의 조건문들을 수행하고, 조건이 참이라면 해당 라인을 실행하고, 조건이 해당하지 않으면 해당 태그는 무시하게 된다.

자바의 조건문중 switch 문도 사용할 수 있다.


주석

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>예시</h1>

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

<h1>1. 표준 HTML 주석</h1>
<!--
<span th:text="${data}">html data</span>
-->

<h1>2. 타임리프 파서 주석</h1>
<!--/* [[${data}]] */-->

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

<h1>3. 타임리프 프로토타입 주석</h1>
<!--/*/
<span th:text="${data}">html data</span>
/*/-->

</body>
</html>

1. 표준 HTML 주석 (<!-- 내용 -->)은 그냥 HTML 에서 사용하는 주석으로 타임리프가 건들지 않고 그대로 남겨둔다

2. 타임리프 파서 주석 (<!--/* 내용 */-->) 은 타임리프의 주석으로 타임리프 렌더링시 주석을 제거한다.

3. 타임리프 프로토 타입 주석 (<!--/*/ 내용 /*/-->) 은 HTML 파일을 그대로 열어보면 주석 처리가 되지만, 타임리프로 렌더링하게 되면 렌더링이 되어 내용이 보이는 주석이다.

렌더링 결과


블록

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

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

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

</body>
</html>

두 태그에 대한 반복문이 필요할 때, 한 태그 안에만 속성을 정의하면 스코프가 맞지 않아 애매한 상황이 발생한다.

이때는 block 레벨의 속성을 정의하여 <block> 태그 내부의 모든 값에 접근할 수 있도록 하는 very 편리한 기능이다.

'Spring > Thymeleaf' 카테고리의 다른 글

[Thymeleaf] 타임리프와 스프링의 통합 1 - 입력 폼 처리하기  (0) 2025.06.29
[Thymeleaf] 타임리프 기본 기능 4 - 템플릿 조각과 레이아웃  (0) 2025.06.29
[Thymeleaf] 타임리프 기본 기능 3 - 자바 스크립트 인라인  (0) 2025.06.29
[Thymeleaf] 타임리프 기본 기능 1 - 텍스트 , 표준 표현식 구문  (0) 2025.06.28
[Thymeleaf] Thymeleaf를 소개합니다 !  (0) 2025.06.25
'Spring/Thymeleaf' 카테고리의 다른 글
  • [Thymeleaf] 타임리프 기본 기능 4 - 템플릿 조각과 레이아웃
  • [Thymeleaf] 타임리프 기본 기능 3 - 자바 스크립트 인라인
  • [Thymeleaf] 타임리프 기본 기능 1 - 텍스트 , 표준 표현식 구문
  • [Thymeleaf] Thymeleaf를 소개합니다 !
xuv2
xuv2
집에 가고 싶다
  • xuv2
    xuvlog
    xuv2
  • 전체
    오늘
    어제
    • 전체 글 모아보기 (173) N
      • 잡담 (9)
      • 도전 , 자격증 (2)
      • Error (6) N
      • Java (23)
      • Spring (40)
        • Core (10)
        • MVC (21)
        • Thymeleaf (9)
      • DataBase (6)
        • Database Modeling (4)
        • SQL (2)
      • HTTP (11)
      • Network (17)
      • Software Engineering (3)
      • Operating System (3)
      • Algorithm (16)
      • Project (19)
        • Web (9)
        • iOS (8)
        • Python (1)
        • Toy Project (1)
      • A.I (13)
      • Linux (5)
  • 블로그 메뉴

    • 홈
  • 링크

    • Github
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
xuv2
[Thymeleaf] 타임리프 기본 기능 2 - 속성 값 설정, 반복, 조건부 평가, 주석, 블록
상단으로

티스토리툴바