프로그래밍 언어/Thymeleaf

[Thymeleaf] if문, 조건문으로 속성 추가 및 클래스 적용

이로률 2025. 2. 28. 17:39

1. th:if

th:if="${session.name} != null" th:text="|${session.name} 님|"
th:if="${session.name} == null" th:text="Login"

2. th:if - th:unless

th:if="${session.name} != null" th:text="|${session.name} 님|"
th:unless="${session.name} != null" th:text="Login"

3. html 속성 조건문으로 추가

1) th:attr

  • th:attr : HTML 요소에 속성을 추가하거나 변경하는 데 사용되는 속성
  • HTML 속성뿐만 아니라, CSS 스타일 및 데이터 속성도 포함

th:attr="속성명=${조건 ? true일 경우 : false일 경우}"

th:attr="class=${current == '4' ? 'navbar fixed-top py-3' : 'navbar navbar-light fixed-top py-3'}"

2) th:classappend

  • th:classappend : HTML 요소에 클래스를 추가하는 데 사용
  • 이 속성은 이미 존재하는 클래스에 새로운 클래스를 추가하는 데 사용
    th:classappend="${isActive} ? 'active' : ''"