twig: 複数の条件を持つIF 質問する

twig: 複数の条件を持つIF 質問する

twig if ステートメントに問題があるようです。

{%if fields | length > 0 || trans_fields | length > 0 -%}

エラーは次のとおりです:

Unexpected token "punctuation" of value "|" ("name" expected) in 

なぜこれが機能しないのか理解できません。まるで、小枝がすべてのパイプとともに失われたかのようです。

私はこれを試しました:

{% set count1 = fields | length %}
{% set count2 = trans_fields | length %}
{%if count1 > 0 || count2 > 0 -%}

しかし、if も失敗します。

次にこれを試しました:

{% set count1 = fields | length > 0 %}
{% set count2 = trans_fields | length > 0 %}
{%if count1 || count2 -%}

それでもまだ機能せず、毎回同じエラーが発生します...

それで、本当に単純な質問が生まれました。Twig は複数の条件 IF をサポートしていますか?

ベストアンサー1

私の記憶が正しければ、Twig は||and&&演算子をサポートしていませんが、それぞれorandを使用する必要があります。技術的には必須ではありませんが、2 つのステートメントをより明確に示すために括弧を使用することもあります。

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

表現

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

おすすめ記事