Is there a Twig shorthand syntax for outputting conditional text Is there a Twig shorthand syntax for outputting conditional text php php

Is there a Twig shorthand syntax for outputting conditional text


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


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


The null-coalescing operator also working, like:

{% set avatar = blog.avatar ?? 'https://example.dev/brand/avatar.jpg' %}