source

Tymeleaf: 변수가 정의되어 있는지 확인합니다.

bestscript 2023. 3. 6. 21:13

Tymeleaf: 변수가 정의되어 있는지 확인합니다.

변수Tymeleaf에 정의되어 있는지 어떻게 확인할 수 있습니까?

Javascript에서는 다음과 같습니다.

if (typeof variable !== 'undefined') { }

또는 PHP에서 다음을 수행합니다.

if (isset($var)) { }

Tymeleaf에 동등한 것이 있나요?

예, 다음 코드를 사용하여 문서에 대한 지정된 속성이 있는지 쉽게 확인할 수 있습니다.주의: 작성 중div조건을 만족하는 경우 태그 지정:

<div th:if="${variable != null}" th:text="Yes, variable exists!">
   I wonder, if variable exists...
</div>

사용하고 싶은 경우variable의 필드 이 필드가 존재하는지 확인할 필요가 있습니다.

<div th:if="${variable != null && variable.name != null}" th:text="${variable.name}">
   I wonder, if variable.name exists...
</div>

또는 if 문을 사용하지 않고 더 짧게 할 수도 있습니다.

<div th:text="${variable?.name}">
   I wonder, if variable.name exists...
</div>`

그러나 이 문을 사용하면 생성은 종료됩니다.div가부를 태그하다variable또는variable.name존재하다

당신은 여기서 백리엽의 조건들에 대해 더 배울 수 있습니다.

짧은 형식:

<div th:if="${currentUser}">
    <h3>Name:</h3><h3 th:text="${currentUser.id}"></h3>
    <h3>Name:</h3><h3 th:text="${currentUser.username}"></h3>
</div>

콘텍스트에 특정 변수가 포함되어 있는지 여부를 확인하려면 콘텍스트 변수 맵에 직접 문의할 수 있습니다.이를 통해 변수가 정의되어 있지만 값이 null인 경우와는 달리 변수가 지정되었는지 여부를 판단할 수 있습니다.

티멜리프 2

오브젝트의 메서드를 사용합니다.

<div th:if="${#vars.containsKey('myVariable')}" th:text="Yes, $myVariable exists!"></div>

티멜리프 3

오브젝트의 메서드를 사용합니다.

<div th:if="${#ctx.containsVariable('myVariable')}" th:text="Yes, $myVariable exists!"></div>

조건부 연산자를 사용할 수 있습니다.변수(존재하는 경우) 또는 빈 문자열이 기록됩니다.

<p th:text="${variable}?:''"></p>

언급URL : https://stackoverflow.com/questions/28783385/thymeleaf-check-if-a-variable-is-defined