2011-12-05 49 views
95

看來我有枝條如果語句有問題。枝條:如果有多個條件

{%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 -%} 

但如果還失敗。

然後嘗試這樣:

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

,它仍然無法正常工作,同樣的錯誤每次...

所以......導致我一個非常簡單的問題:不支持枝杈多種條件IF?

回答

229

如果我記得正確Twig不支持||&&運營商,但要求分別使用orand。我還會用括號來更清楚地表示這兩個陳述,雖然這在技術上並不是必需的。

{%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)) %} 
+13

當然,我沒有發現的機會在查看IF文檔時,精彩且節省時間的表格:http://twig.sensiolabs.org/doc/tags/if.html感謝您的解決方案! – FMaz008

+5

他們傾向於使用github上的wiki來更徹底地記錄他們的代碼。該表來自[此處](https://github.com/vito/chyrp/wiki/Twig-Reference) –

+14

此外,運營商區分大小寫。 OR不起作用。 – Acyra