php 树枝:如果有多个条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8388537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
twig: IF with multiple conditions
提问by FMaz008
It seem I have problem with a twig if statement.
似乎我对树枝 if 语句有问题。
{%if fields | length > 0 || trans_fields | length > 0 -%}
The error is:
错误是:
Unexpected token "punctuation" of value "|" ("name" expected) in
I can't understand why this doesn't work, it's like if twig was lost with all the pipes.
我不明白为什么这不起作用,就像所有管道都丢失了树枝一样。
I've tried this :
我试过这个:
{% set count1 = fields | length %}
{% set count2 = trans_fields | length %}
{%if count1 > 0 || count2 > 0 -%}
but the if also fail.
但如果也失败。
Then tried this:
然后尝试了这个:
{% set count1 = fields | length > 0 %}
{% set count2 = trans_fields | length > 0 %}
{%if count1 || count2 -%}
And it still doesn't work, same error every time ...
它仍然不起作用,每次都出现相同的错误......
So... that lead me to a really simple question: does Twig support multiple conditions IF ?
所以......这让我想到了一个非常简单的问题:Twig 是否支持多个条件 IF ?
回答by Ben Swinburne
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
如果我没记错的话,Twig 不支持||
and&&
运算符,但需要分别使用or
and and
。我还会使用括号更清楚地表示这两个语句,尽管这在技术上不是必需的。
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
表达式
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)) %}