2011-12-05 159 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