148

ifThymeleafで簡単に行うための最良の方法は何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タグを使用することです。たとえばh2、とspan

それを達成するためのより良い方法を提案できますか?

4

11 に答える 11

234

Thymeleafには、 Thymeleaf 2.0で導入された<c:choose>and <c:when>th:switchand属性と同等の属性があります。th:case

*これらは、デフォルトの場合に使用して、期待どおりに機能します。

<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の作成者です。

于 2012-11-28T09:24:14.333 に答える
126

このコードを試して、顧客がログインしているか匿名かを調べました。th:ifとのth: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>
于 2013-01-02T11:51:14.303 に答える
30

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 テンプレート コードの「真/偽」の結果を生成する「認証」および「承認」ユーティリティ オブジェクトが混在する複雑な式です。

'authentication' および 'authorization' ユーティリティ オブジェクトは、thymeleaf エクストラ springsecurity3 ライブラリから取得されました。'authentication' オブジェクトが利用できない場合、または authorization.expression('isAuthenticated()') が 'false' と評価される場合、expression は ${false} を返し、それ以外の場合は ${true} を返します。

于 2013-01-14T11:10:13.080 に答える
21

使用できます

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

例:

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

同じ質問をする新しい人に役立つかもしれません。

于 2014-04-25T17:05:05.783 に答える
14

別の解決策 - ローカル変数を使用できます。

<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

于 2015-10-06T09:37:49.140 に答える
10

より単純な場合 (html タグが同じ場合):

<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>
于 2017-04-01T19:47:00.680 に答える