Twig三元运算符,Shorthand if then else



Twig是否支持三元运算符(简写为else)?

我需要一些条件逻辑,比如:

{%if ability.id in company_abilities %}
    <tr class="selected">
{%else%}
    <tr>
{%endif%}

但使用Twig中的简写。

{{ (ability.id in company_abilities) ? 'selected' : '' }}

三元运算符记录在"其他运算符"中

您可以使用Twig 1.12.0 的简写语法

{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}

Twig 1.12.0中添加了对扩展三元运算符的支持。

  1. 如果foo回波yes,则回波no:

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

    {{ foo ?: 'no' }}
    

    {{ foo ? foo : 'no' }}
    
  3. 如果foo回波yes,则无回波:

    {{ foo ? 'yes' }}
    

    {{ foo ? 'yes' : '' }}
    
  4. 返回foo的值,如果它是定义的并且不为null,则返回no,否则:

    {{ foo ?? 'no' }}
    
  5. 返回foo的值,如果它是定义的值也计数),否则返回no

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

例如,如果数据库中存在价格,则打印(价格为$$$),其他打印(不可用),~用于Twig中的串联。

{{ Price is defined ? 'Price is '~Price : 'Not Available' }}

我刚刚使用a作为通用变量名。你也可以使用无尽的,如果其他类似:

{{ a == 1 ? 'first' : a == 2 ? 'second' : 'third' }}

最新更新