[Spring Boot] Thymeleaf 타임리프 템플릿 사용하기 (6) :: Thymeleaf에서 HTML 속성 조작하기
by 캐떠린th: 문법을 사용하여 HTML 속성을 조작해보자!
저번 포스팅에서 사용했던 프로젝트에 이어서 작업하기
HTML 속성 조작하기
1. TestController.java
@GetMapping(value = "/m5.do")
public String m5(Model model) {
//HTML 속성 조작
model.addAttribute("size", 50);
model.addAttribute("name", "홍길동");
model.addAttribute("color", "cornflowerblue");
return "m5";
}
2. m5.html
<!DOCTYPE html>
<html xmlns:th="https://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
.one { color: blue; }
.two { background: yellow; }
.three { text-decoration: underline; }
</style>
</head>
<body>
<h1>HTML Attributes</h1>
<input type="text" name="age" size="50">
<br>
<input type="text" name="age" size="${size}">
<br>
<input th:type="text" th:name="age" th:size="${size}">
<br>
<input type="text" th:value="${name}">
<hr>
<div class="one">Box</div>
<div th:class="one">Box</div>
<!-- 동일 속성을 동시에 적을 수 있다. 그 경우에 무조건 th:가 우선 적용된다. 위의 경우 th:class가 우선 적용된다. -->
<div class="one" th:class="two">Box</div>
<!-- 두가지 속성 동시 적용 -->
<div class="one" th:attrappend="class=' two'">Box</div>
<div class="one" th:attrprepend="class='two '">Box</div>
<!-- 원래 attrappend는 아래와 같은 경우에 사용한다. 특정 속성값에 누적해서 사용. -->
<input type="text" value="이름: ">
<input type="text" th:value="'이름: ' + ${name}">
<input type="text" th:value="|이름: ${name}|">
<input type="text" value="이름: " th:attrappend="value=${name}">
<hr>
<div class="one" th:classappend="tow">Box</div>
<hr>
<input type="checkbox" name="cb" checked>
<input type="checkbox" name="cb" th:checked="true">
<input type="checkbox" name="cb" th:checked="false">
<input type="checkbox" name="cb" th:checked="${size > 0}">
<input type="checkbox" name="cb" th:checked="${size < 0}">
<hr>
<div style="background-color: ${color};">Box</div> <!-- 적용 불가. ${}를 사용하려면 th 속성(Thymeleaf 속성)에서 사용가능하다. -->
<div th:style="'background-color: ' + ${color}">Box</div>
<div th:style="|background-color: ${color}|"></div>
</body>
</html>
${...} 표현식은 th 속성에만 사용 가능하다.
- HTML 속성 조작 방법: th:HTML속성명 = 값
- ex) <input th:type="text" th:name="age" th:size="${size}"> </aside>
기존 HTML 속성과 th 속성 사용 시, 동일 속성을 동시에 적을 수 있다. 이 경우에는 무조건 th:가 우선 적용된다.
동일 속성을 중복 적용 하기 위해
- th:attrappend
- th:attrprepend
사용이 가능하지만, class 속성의 경우 두 클래스를 구분하기 위해 문자열 앞 또는 뒤에 스페이스(공백)이 포함되어야 하는 불편함이 있다.
ex) <div class="one" th:attrappend="class=' two'">Box</div>
<div class="one" th:attrprepend="class='two '">Box</div>
따라서 이 경우에는 th:classappend를 사용하면 공백 상관 없이 편하게 사용할 수 있다.
ex) <div class="one" th:classappend="two">Box</div>
*글 작성에 참고한 내용: 학원 쌤의 열정적인 수업
'Spring' 카테고리의 다른 글
블로그의 정보
All of My Records
캐떠린