web-dev-qa-db-ja.com

小枝:複数の条件がある場合

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

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

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

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

なぜこれが機能しないのか理解できません。すべてのパイプでtwigが失われたかのようです。

私はこれを試しました:

{% 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をサポートしますか?

110
FMaz008

正しく思い出すと、Twigは||および&&演算子をサポートしていませんが、それぞれorおよびandを使用する必要があります。技術的には必須ではありませんが、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.

より複雑な操作の場合、混乱を避けるために個々の式を括弧で囲むのが最善かもしれません。

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