Is there a Twig shorthand syntax for outputting conditional text

前端 未结 3 1295
有刺的猬
有刺的猬 2021-02-02 04:51

Is there a shorter syntax in Twig to output a conditional string of text?

{% if not info.id %}create{% else %}edit{% endif %}

相关标签:
3条回答
  • 2021-02-02 05:28

    This should work:

    {{ not info.id ? 'create' : 'edit' }}
    

    Also, this is called the ternary operator. It's kind of hidden in the documenation: twig docs: operators

    From their documentation the basic structure is:

    {{ foo ? 'yes' : 'no' }}
    
    0 讨论(0)
  • 2021-02-02 05:47

    If you need to compare the value is equal to something you can do :

    {{  user.role == 'admin' ? 'is-admin' : 'not-admin' }}
    

    You can use the Elvis Operator inside twig :

    {{  user ? 'is-user' }} 
    
    {{  user ?: 'not-user' }} // note that it evaluates to the left operand if true ( returns the user ) and right if not
    
    0 讨论(0)
  • 2021-02-02 05:48

    The null-coalescing operator also working, like:

    {% set avatar = blog.avatar ?? 'https://example.dev/brand/avatar.jpg' %}
    
    0 讨论(0)
提交回复
热议问题