BackEnd/Thymeleaf

[Thymeleaf] 속성 값 설정

샤아이인 2022. 1. 27.

인프런 김영한님의 Spring강의에서 공부한것을 올리며, Thymeleaf의 경우 unit 단위로 공부후 각각 정리하는 글을 작성하겠습니다.

 

속성 값 설정

타임리프에서 속성값을 지정할때는 th:* 와 같이 속성을 적용하면 기존 속성을 대체한다. 만약 기존 속성이 없다면 새로 만든다.

 

우선 컨트롤러부터 하나 만들어 봅시다.

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

아주 간단한 컨트롤러 입니다. 이제 이를 처리할 뷰는 다음과 같습니다.

<!DOCTYPE html>
<html lang="en">
<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" /> 
 

원래 첫줄처럼 name 속성의 값은 "mock"이다. 하지만 타임리프를 적용하면 치환되는데 그결과는 두번째 줄과 같다.

name 속성의 값이 th:name의 값으로 변경된것 이다.

 

▶ 속성 추가

th:attrappend : 속성 값의 뒤에 값을 추가한다.

th:attrprepend : 속성 값의 앞에 값을 추가한다.

th:classappend : class 속성에 자연스럽게 추가한다. (은근 자주 사용)

 

▶ checked 처리

HTML에서 checked 속성을 사용한다면 자동으로 체크박스에 체크를 해준다. 개발자가 체크를 하지 않아도 말이다.

<input type="checkbox" name="active" checked="false" />
 

예를 들어 위와 같은 태그를 사용하면 checked="false" 임에도 불구하고 랜더링 하면 체크박스가 체크 되어 있다.

HTML에서는 checked의 속성값에 상관없이 checked 라는 속성만 있어도 체크가 되기 때문이다.

 

타임리프의 th:checked 는 값이 false 인 경우 checked 속성 자체를 제거한다.

<input type="checkbox" name="active" th:checked="false" />
타임리프 렌더링 후: <input type="checkbox" name="active" />
 

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

[Thymeleaf] 조건부 평가  (0) 2022.01.27
[Thymeleaf] 반복  (0) 2022.01.27
[Thymeleaf] 연산  (0) 2022.01.26
[Thymeleaf] Literals  (0) 2022.01.26
[Thymeleaf] URL 링크  (0) 2022.01.26

댓글