웹 화면을 만들다 보면 HTML 태그의 속성을 동적으로 바꿔야 하는 경우가 많다.
예를 들어, input 태그의 name, class 같은 속성을 서버 데이터에 따라 변경하거나, 체크박스의 checked 여부를 조건에 맞게 처리해야 할 수도 있다.
이번 글에서는 타임리프가 제공하는 속성 제어 기능을 정리해 본다.
- th:* 속성을 이용한 기본 속성 대체
- th:attrappend / th:attrprepend / th:classappend 를 이용한 속성 값 추가
- th:checked 를 이용한 체크박스 처리
하나씩 예제와 함께 살펴보자.
1. 컨트롤러에서 뷰 호출하기
속성 제어는 서버 데이터를 직접 쓰지 않아도 설명할 수 있으므로 단순히 템플릿을 리턴하는 컨트롤러만 준비한다.
@GetMapping("/attribute")
public String attribute() {
return "basic/attribute";
}
2. 뷰 템플릿 예제
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<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>
3. 실행 결과와 동작 방식
(1)속성 설정 (th:name)
<input type="text" name="mock" th:name="userA" />
→ 렌더링 후:
<input type="text" name="userA" />
(2)속성 추가
- th:attrappend: 기존 속성 값 뒤에 추가
- th:attrprepend: 기존 속성 값 앞에 추가
- th:classappend: CSS class 속성에 자연스럽게 추가
예를 들어:
<input type="text" class="text" th:classappend="large" />
→ 렌더링 후:
<input type="text" class="text large" />
(3)체크박스 처리 (th:checked)
HTML에서 체크박스는 checked="false" 라고 해도 단순히 checked 속성이 존재하기 때문에 무조건 체크된다.
<input type="checkbox" name="active" checked="false" />
→ 브라우저에서는 체크됨
이런 문제를 해결하기 위해 Thymeleaf는 th:checked를 제공한다.
- th:checked="true" → checked 속성이 추가되어 체크됨
- th:checked="false" → checked 속성이 아예 제거됨 (체크되지 않음)
마무리하며
이번 글에서는 Thymeleaf의 속성 제어 기능을 살펴보았다.
- th:* 로 속성을 대체하거나 추가할 수 있고
- th:checked 로 HTML 체크박스의 불편한 동작을 보완할 수 있다.
이 기능들을 활용하면 서버 데이터나 조건에 맞춰 속성을 유연하게 제어할 수 있고, HTML 템플릿 코드의 가독성도 높아질 것이다.
감사합니다.
'타임리프' 카테고리의 다른 글
| [Thymeleaf] 조건부 평가 (if, unless, switch) (0) | 2025.09.16 |
|---|---|
| [Thymeleaf] 반복 (0) | 2025.09.16 |
| [Thymeleaf] 연산 (0) | 2025.09.15 |
| [Thymeleaf] 리터럴 (1) | 2025.09.15 |
| [Thymeleaf] URL링크 (0) | 2025.09.15 |
