php Twig 三元运算符,简写 if-then-else
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11820297/
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 ternary operator, Shorthand if-then-else
提问by Meliborn
Does Twig support ternary operator?
Twig 是否支持三元运算符?
I need some conditional logic like:
我需要一些条件逻辑,例如:
{%if ability.id in company_abilities %}
<tr class="selected">
{%else%}
<tr>
{%endif%}
but using shorthand in Twig.
但在 Twig 中使用速记。
回答by Ben Swinburne
{{ (ability.id in company_abilities) ? 'selected' : '' }}
The ternary operator is documented under 'other operators'
三元运算符记录在“其他运算符”下
回答by mgalic
You can use shorthand syntax as of Twig 1.12.0
您可以使用 Twig 1.12.0 的速记语法
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
回答by Pmpr
Support for the extended ternary operator was added in Twig 1.12.0.
在Twig 1.12.0中添加了对扩展三元运算符的支持。
If
fooechoyeselse echono:{{ foo ? 'yes' : 'no' }}If
fooecho it, else echono:{{ foo ?: 'no' }}or
{{ foo ? foo : 'no' }}If
fooechoyeselse echo nothing:{{ foo ? 'yes' }}or
{{ foo ? 'yes' : '' }}Returns the value of
fooif it is definedand not null,nootherwise:{{ foo ?? 'no' }}Returns the value of
fooif it is defined(emptyvalues also count),nootherwise:{{ foo|default('no') }}
如果
foo回声yes其他回声no:{{ foo ? 'yes' : 'no' }}如果
foo回声,否则回声no:{{ foo ?: 'no' }}或者
{{ foo ? foo : 'no' }}如果
fooechoyeselse 不回显:{{ foo ? 'yes' }}或者
{{ foo ? 'yes' : '' }}返回的值,
foo如果定义和不为空,no否则:{{ foo ?? 'no' }}foo如果已定义则返回值(空值也算),no否则:{{ foo|default('no') }}

