Ternary operators in Twig php (Shorthand form of if-then-else)

旧街凉风 提交于 2019-11-28 15:45:32
{{ (ability.id in company_abilities) ? 'selected' : '' }}

The ternary operator is documented under 'other operators'

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' : '' }}
Pmpr

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 ''.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!