Twig ternary operator, Shorthand if-then-else

后端 未结 3 1322
眼角桃花
眼角桃花 2020-12-12 13:32

Does Twig support ternary (shorthand if-else) operator?

I need some conditional logic like:

{%if ability.id in company_abilities %}
    

        
相关标签:
3条回答
  • 2020-12-12 13:48
    {{ (ability.id in company_abilities) ? 'selected' : '' }}
    

    The ternary operator is documented under 'other operators'

    0 讨论(0)
  • 2020-12-12 13:48

    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' : '' }}
    
    0 讨论(0)
  • 2020-12-12 13:52

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

    1. If foo echo yes else echo no:

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

      {{ foo ?: 'no' }}
      

      or

      {{ foo ? foo : 'no' }}
      
    3. If foo echo yes else echo nothing:

      {{ foo ? 'yes' }}
      

      or

      {{ foo ? 'yes' : '' }}
      
    4. Returns the value of foo if it is defined and not null, no otherwise:

      {{ foo ?? 'no' }}
      
    5. Returns the value of foo if it is defined (empty values also count), no otherwise:

      {{ foo|default('no') }}
      
    0 讨论(0)
提交回复
热议问题