Programing

Thymeleaf에서 if-else를 수행하는 방법?

lottogame 2020. 7. 22. 21:50
반응형

Thymeleaf에서 if-else를 수행하는 방법?


Thymeleaf에서 간단한 if-else를 수행하는 가장 좋은 방법은 무엇입니까?

나는 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}".

하자의 말 : 중요한 것은 내가 2 개 개의 다른 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 자습서) http://www.thymeleaf.org/whatsnew20.html#swit참조 하십시오 .

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>

As explained in the documentation, it's the same thing as using th:unless. As other answers have explained:

Also, th:if has an inverse attribute, th:unless, which we could have used in the previous example instead of using a not inside the OGNL expression

Using not also works, but IMHO it is more readable to use th:unless instead of negating the condition with not.


<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>


<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>

<div style="width:100%">
<span th:each="i : ${#numbers.sequence(1, 3)}">
<span th:if="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-success custom-width" th:text="${i}"></a
</span>
<span th:unless="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-danger custom-width" th:text="${i}"></a> 
</span>
</span>
</div>

enter image description here

참고URL : https://stackoverflow.com/questions/13494078/how-to-do-if-else-in-thymeleaf

반응형