Thymeleaf에서 if-else를 수행하는 방법? <h2>Hello!</h2> </c:when> <c:otherwise>

간단하게 할 수있는 가장 좋은 방법은 무엇입니까 ifelseThymeleaf의는?

나는 Thymeleaf에서와 동일한 효과를 달성하고 싶습니다

<c:choose>
  <c:when test="${potentially_complex_expression}">
     <h2>Hello!</h2>
  </c:when>
  <c:otherwise>
     <span class="xxx">Something else</span>
  </c:otherwise>
</c:choose>

JSTL에서.

내가 지금까지 생각한 것 :

<div th:with="condition=${potentially_complex_expression}" th:remove="tag">
    <h2 th:if="${condition}">Hello!</h2>
    <span th:unless="${condition}" class="xxx">Something else</span>
</div>

potentially_complex_expression두 번 평가하고 싶지 않습니다 . 그래서 로컬 변수를 도입했습니다 condition. 그럼에도 불구하고 나는 모두를 사용하여 싫어 th:if="${condition}하고 th:unless="${condition}".

하자의 말 : 중요한 것은 내가 두 개의 서로 다른 HTML 태그를 사용한다는 것입니다 h2span.

그것을 달성하는 더 좋은 방법을 제안 할 수 있습니까?



답변

Thymeleaf은에 동등 물이있다 <c:choose>하고 <c:when>다음을 th:switch하고 th:caseThymeleaf 2.0에 도입 된 속성.

*기본 사례를 사용하여 예상대로 작동합니다 .

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

구문 (또는 Thymeleaf 자습서)에 대한 빠른 설명은 내용을 참조하십시오 .

면책 조항 : StackOverflow 규칙에 따라 Thymeleaf의 저자입니다.


답변

이 코드를 사용하여 고객이 로그인했는지 또는 익명인지 확인했습니다. 내가 사용했던 th:ifth:unless조건식. 아주 간단한 방법입니다.

<!-- IF CUSTOMER IS ANONYMOUS -->
<div th:if="${customer.anonymous}">
   <div>Welcome, Guest</div>
</div>
<!-- ELSE -->
<div th:unless="${customer.anonymous}">
   <div th:text=" 'Hi,' + ${customer.name}">Hi, User</div>
</div>


답변

Daniel Fernández 외에도 보안과 관련된 예제를 공유하고 싶습니다.

<div th:switch="${#authentication}? ${#authorization.expression('isAuthenticated()')} : ${false}">
    <span th:case="${false}">User is not logged in</span>
    <span th:case="${true}">Logged in user</span>
    <span th:case="*">Should never happen, but who knows...</span>
</div>

다음은 thymeleaf 템플릿 코드에 대해 ‘true / false’결과를 생성하는 ‘authentication’및 ‘authorization’유틸리티 객체가 혼합 된 복잡한 표현입니다.

‘authentication’및 ‘authorization’유틸리티 오브젝트는 thymeleaf extras springsecurity3 library 에서 가져 왔습니다 . ‘authentication’오브젝트를 사용할 수 없거나 authorization.expression ( ‘isAuthenticated ()’)이 ‘false’로 평가되면 $ {false}를 리턴하고 그렇지 않으면 $ {true}를 리턴합니다.


답변

당신이 사용할 수있는

If-then-else:  (if) ? (then) : (else)

예:

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

새로운 사람들이 같은 질문을하는 데 유용 할 수 있습니다.


답변

다른 해결책-지역 변수를 사용할 수 있습니다.

<div th:with="expr_result = ${potentially_complex_expression}">
    <div th:if="${expr_result}">
        <h2>Hello!</h2>
    </div>
    <div th:unless="${expr_result}">
        <span class="xxx">Something else</span>
    </div>
</div>

지역 변수에 대한 추가 정보 :
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#local-variables


답변

더 간단한 경우 (html 태그가 동일한 경우) :

<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>


답변

다른 해결책은 not반대의 부정을 얻기 위해 사용 하고 있습니다.

<h2 th:if="${potentially_complex_expression}">Hello!</h2>
<span class="xxx" th:if="${not potentially_complex_expression}">Something else</span>

설명서에 설명 된 대로 사용하는 것과 같습니다 th:unless. 다른 답변에서 설명했듯이 :

또한 th:if역 속성이 있습니다.이 속성 은 OGNL 표현식 내부에서 not을 사용하는 대신th:unless 이전 예제에서 사용할 수있었습니다.

를 사용하면 not작동하지만 IMHO로 th:unless조건을 부정하는 대신 사용하기가 더 쉽습니다 not.