Thymeleaf (if, unless)

2024. 6. 14. 19:07JSP+Spring Boot

th:if=${조건식}
    - 조건식이 true인 경우에만 해당 속성이 작성된 요소를 화면에 출력
   ex) th:if${만약 관리자가 접속했다면} = 상품 수정하기를 보여주겠다

th:unless=${조건식}
     - 조건식이 false인 경우에만 해당 속성이 작성된 요소를 화면에 출력
    ex) th:unless=${비밀번호가 일치하지 않는다면} = 비밀번호 찾기 버튼 보여줌

 

    <th:block th:if="${std == null}">
    <!-- std == null -> 값이 없을 경우 -->
         <h4>std 값 없음</h4>
    </th:block>
    <th:block th:unless="${std == null}">
    <!-- std != null -> 값이 있을 경우 -->
         <h4>std 값 있음</h4>
    </th:block>
    
    <th:block th:if="${mem == null}">
    <!-- mem == null -> 값 없음 -->
    	<h4>mem값 없음</h4>
    </th:block>
    <th:block th:unless="${mem == null}">
    <!-- mem != null 값 있음 -->
    	<h4>mem값 있음</h4>
    </th:block>
<th:block th:if="${std == null}">
<!-- std == null -> 값이 없을 경우 -->
     <h4>std 값 없음</h4>
</th:block>
<th:block th:unless="${std == null}">
<!-- std == null -> 값이 있을 경우 -->
     <h4>std 값 있음</h4>
</th:block>

<th:block th:if="${mem == null}">
<!-- mem == null -> 값 없음 -->
    <h4>mem값 없음</h4>
</th:block>
<th:block th:unless="${mem == null}">
<!-- mem != null 값 있음 -->
    <h4>mem값 있음</h4>
</th:block>

 

둘 다 값을 주입해서 값 있음으로 뜬다

 

 

 

th:if / th:unless 조건식이 변수명 / 값 하나만 작성한 경우

  if문에 작성된 값이 있으면 (값 != null) -> true
  if문에 작성된 값이 없으면 (값 == null) -> false

 

<h4 th:if="${std}">std 값이 존재합니다. ${std == null}에서 '== null' 생략</h4>

<!-- Controller에서 temp에 model.addAttribute로 전달한 값이 없으므로 
화면에 temp로 지정된 태그는 보이지 않음-->
<h4 th:if="${temp}">temp로 지정된 값이 존재합니다.</h4>

 

temp 값은 넣지 않아서 false이므로 보이지 않는다.

 

 

 

 

'JSP+Spring Boot' 카테고리의 다른 글

Thymeleaf(inline, classappend), sequence  (0) 2024.06.14
Thymeleaf(switch, case)  (0) 2024.06.14
Thymeleaf(parameter, utext)  (0) 2024.06.14
Thymeleaf로 객체 값 얻어오기  (1) 2024.06.14
Thymeleaf(block, text, each)  (0) 2024.06.14