본문 바로가기
Thymeleaf

[Thymeleaf] 타임리프 에서 null과 빈 문자열 확인하기

by 무사뎀벨레 2023. 1. 31.

 

 

 

 

기존의 null값과 빈 문자열(" ") 확인


기존 방식은 null값빈 문자열각각 확인하였습니다.

<!-- null값 체크 -->
<div th:if="${player.num != null}" th:text="${player.name}"></div>

<!-- 빈 문자열 체크 -->
<div th:if="${player.num != ''}" th:text="${player.name}"></div>

 

 

 

 

 

 

 

#strings. isEmpty를 통한 null값빈 문자열(" ") 확인


#strings. isEmpty(확인할 값)

의 형태로 null값빈 문자열(" ")을 한 번에 확인할 수 있습니다.

 

타임리프의 isEmpty 함수전달되는 매개변수가 null값인지, 그리고 빈 문자열(" ")인지 확인하여
맞다면 true 아니라면 false리턴합니다.

 

 

아래의 코드를 통해 자세한 사용 예시를 확인할 수 있습니다.

<div th:if="${not #strings.isEmpty(player.num)}" th:text="${player.name}"></div>

#strings. isEmpty를 통하여 매개변수인 player.num의 값이 null인지 빈 문자열(" ")인지 확인합니다.

 

 

#strings. isEmpty앞에 not을 붙인 th:if="${not #strings.isEmpty(player.num)}"를 통해 player.num 값이 null이 아니고 빈 문자열도 아니라면 true를 반환하게 하여 th:text="${player.name}"를 출력하게 됩니다.

 

 

#strings. isEmpty를 사용할 때 참고해야 할 사항이 있다면, isEmpty 함수trim 함수를 적용하기 때문에 빈 줄이나 공백도 같이 걸러진다는 것을 유의해야 합니다.

 

 

타임리프의 다른 함수를 살펴보려면 아래의 링크를 확인해 보세요.

https://hajoung56.tistory.com/72

 

[Thymeleaf] 타임리프 주요 기능 유틸리티 - Utility Objects(Strings, Numbers, Objects, Arrays, Lists, Maps, Messages,

아래 링크와 같이 이전에는 타임리프 정의와 사용방법에 기본적인 기능들을 간단히 설명하였지만, 이번 글에서 주요 유틸리티를 안내합니다. [Thymeleaf] 정의와 사용방법 Thymeleaf의 정의와 사용하

hajoung56.tistory.com

 

반응형

댓글