타임리프 - 속성값 설정

신창호·2022년 11월 24일
0

thymeleaf

목록 보기
4/4

속성 값 설정

  • 타임리프는 text말고도 속성에도 적용할 수 있다.
    • 주로 HTML 태그에 th:* 속성을 지정하는 방식으로 동작한다.
    • th:* 로 속성을 적용하면 기존 속성을 대체한다.
    • 기존 속성이 없으면 새로 만든다






예시

controller

  • 넘겨주는 값 없이 뷰템플릿을 호출만 한다.
@GetMapping("/attribute")
public String attribute() {
        return "basic/attribute";
}






HTML

속성 설정

  • 먼저 기본적으로 input태그에 이름을 지어주고, 타임리프 속성을 적용해보자
  • html파일에서 th는 무시되기때문에 mock으로 적용된다.
<body>
<h1>속성 설정</h1>
<input type="text" name="mock" th:name="userA" />
</body>



속성 추가

  • 기존 설정해놓은 속성에 추가할 수도 있다.
  • th:attrappend = "속성이름=' 추가할 속성'" 뒤에 추가
  • th:attrpreappend = "속성이름='추가할 속성 '" 앞에 추가
    • 단, attrappend, attrprepend의 경우에 기존 속성에 띄어쓰기 없이 앞뒤로 추가되기 때문에, ''안에 띄어쓰기를 넣어 줘야한다.
  • th:classappend="추가할 속성"
    • 그래서, class의 경우, th:classappend를 사용하면 띄어쓰기 없이 뒤에 추가할 수 있다.
<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/>



checkbox 처리

  • 먼저 예시를 들어가기 앞써, HTML에서 CheckBox의 체크상태는 checked 속성의 유무로 변경할 수 있는 것을 확인했다.



타임리프 checked 처리

  • 하지만, 타임리프를 사용하면 이번엔 class 속성에 추가하는 것이 아닌, checkbox의 속성인 체크상태도 수정할 수 있다.
  • th:checked="true" 면 체크박스가 체크된 상태로
  • th:checked="false"면 체크박스가 언체크된 상태로 출력된다.
<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 /><br/>
profile
한단계씩 올라가는 개발자

0개의 댓글