Ternary operators in Twig php (Shorthand form of i

2019-01-21 03:30发布

Is it possible to use ternary operators in twig template? Now, for adding some class to DOM element depend on some condition I do like this:

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

Instead of

<tr class="<?=in_array($ability->id, $company_abilities) ? 'selected' : ''?>">

in native php template engine.

3条回答
我想做一个坏孩纸
2楼-- · 2019-01-21 04:08
{{ (ability.id in company_abilities) ? 'selected' : '' }}

The ternary operator is documented under 'other operators'

查看更多
相关推荐>>
3楼-- · 2019-01-21 04:08

The ternary operator (?:)

Support for the extended ternary operator was added in Twig 1.12.0.

  1. Case #1

    Snippet:

    {{ foo ? 'yes' : 'no' }}
    

    Evaluates:

    if foo echo yes else echo no


  2. Case #2

    Snippet:

    {{ foo ?: 'no' }}
    

    or

    {{ foo ? foo : 'no' }}
    

    Evaluates:

    if foo echo it, else echo no


  3. Case #3

    Snippet:

    {{ foo ? 'yes' }}
    

    or

    {{ foo ? 'yes' : '' }}
    

    Evaluates:

    if foo echo yes else echo nothing


The null-coalescing operator (??)

  1. Case #1

    Snippet:

    {{ foo ?? 'no' }}
    

    Evaluates:

    Returns the value of foo if it is defined and not null, no otherwise

Note: this is slightly different from {{ foo|default('no') }}, since the latter will be triggered also from empty values like ''.

查看更多
Explosion°爆炸
4楼-- · 2019-01-21 04:15

You can use shorthand syntax as of Twig 1.12.0

{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
查看更多
登录 后发表回答