타임리프 태그 속성(Attribute)

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

th:* 로 속성을 적용하면 기존 속성을 대체합니다. 기존 속성이 없으면 새로 만듭니다.

참고

BasicController 추가

package hello.thymeleaf.basic;

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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/basic")
public class BasicController {

		...

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

		...

}
<!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>
  1. 속성 설정

    th:* 속성을 지정하면 타임리프는 기존 속성을 th:* 로 지정한 속성으로 대체합니다. 기존 속성이 없다면 새로 만듭니다.

    <input type="text" name="mock" th:name="userA" />
    

    → 타임리프 렌더링 후

    <input type="text" name="userA" />
    

    Untitled

    <aside> ✏️ 타임리프는 네츄럴 템플릿이기 때문에 순수 HTML을 그대로 유지합니다.

    그래서 그냥 해당 파일을 열게되면 웹 브라우저는 th: 속성을 알지 못하므로 무시하고 기존의 값에 따라서 화면을 출력합니다.

    참고1, 참고2

    </aside>

  2. 속성 추가

  3. checked 처리

Reference