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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:11:20  来源:igfitidea点击:

Twig ternary operator, Shorthand if-then-else

phptwigconditional-operator

提问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中添加了对扩展三元运算符的支持。

  1. If fooecho yeselse echo no:

    {{ foo ? 'yes' : 'no' }}
    
  2. If fooecho it, else echo no:

    {{ foo ?: 'no' }}
    

    or

    {{ foo ? foo : 'no' }}
    
  3. If fooecho yeselse echo nothing:

    {{ foo ? 'yes' }}
    

    or

    {{ foo ? 'yes' : '' }}
    
  4. Returns the value of fooif it is definedand not null, nootherwise:

    {{ foo ?? 'no' }}
    
  5. Returns the value of fooif it is defined(emptyvalues also count), nootherwise:

    {{ foo|default('no') }}
    
  1. 如果foo回声yes其他回声no

    {{ foo ? 'yes' : 'no' }}
    
  2. 如果foo回声,否则回声no

    {{ foo ?: 'no' }}
    

    或者

    {{ foo ? foo : 'no' }}
    
  3. 如果fooecho yeselse 不回显:

    {{ foo ? 'yes' }}
    

    或者

    {{ foo ? 'yes' : '' }}
    
  4. 返回的值,foo如果定义不为空no否则:

    {{ foo ?? 'no' }}
    
  5. foo如果已定义则返回值(值也算),no否则:

    {{ foo|default('no') }}