오봉이와 함께하는 개발 블로그
스프링 MVC 2 - 타임리프 속성 값 설정 본문
속성 값 설정
타임리프 태그 속성(Attribute)
타임리프는 주로 HTML 태그에 th:*속성을 지정하는 방식으로 사용한다.th:*로 속성을 지정하면 기존 속성을 대체한다.
기존 속성이 없으면 새로 만든다.
예시
@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>
속성 설정
th:*속성을 지정하면 타임리프는 기존 속성을 th:*로 지정한 속성으로 대체한다.<input type="text" name="mock" th:name="userA" />는 <input type="text" name="userA" />로 바뀐다.
속성 추가
th:attrappend : 속성 값의 뒤에 값을 추가한다.
-> <input type="text" class="text" th:attrappend="class=' large'" />는<input type="text" class="text large">로 바뀐다
th:attrprepend : 속성 값의 앞에 값을 추가한다.
-> <input type="text" class="text" th:attrprepend="class='large '" />는<input type="text" class="large text">로 바뀐다.
th:classappend : class 속성 맨뒤에 자연스럽게 추가한다.
-> 띄어쓰기를 해야 하는 번거로움이 있기 때문에 사용한다.
-> <input type="text" class="text" th:classappend="large" />는<input type="text" class="text large">로 바뀐다.
checked 처리
HTML에서는 <input type="checkbox" name="active" checked="false" /> 이 경우에도 checked 속성이 있기 때문에 checked 처리가 되어버린다.
HTML에서 checked속성은 checked속성의 값과 상관없이 checked라는 속성만 있어도 체크가 된다.
이런 부분이 true, false 값을 주로 사용하는 개발자 입장에서는 불편하다.
타임리프의 th:checked는 값이 false인 경우 checked속성 자체를 제거한다.<input type="checkbox" name="active" th:checked="false" />
-> 타임리프 렌더링 후 : <input type="checkbox" name="active">
출처 : 인프런 김영한 지식공유자님 강의 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술
'BE > Thymeleaf' 카테고리의 다른 글
| 스프링 MVC 2 - 타임리프 조건부 평가 (0) | 2022.08.17 |
|---|---|
| 스프링 MVC 2 - 타임리프 반복문 (0) | 2022.08.17 |
| 스프링 MVC 2 - 타임리프 연산 (0) | 2022.08.16 |
| 스프링 MVC 2 - literal(리터럴) (0) | 2022.08.16 |
| 스프링 MVC 2 - 타임리프 URL (0) | 2022.08.16 |