Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sergeifilippov/0378c7c20b383c4edc13869730675ee1 to your computer and use it in GitHub Desktop.
Save sergeifilippov/0378c7c20b383c4edc13869730675ee1 to your computer and use it in GitHub Desktop.
How Twig ternary statements work by John Dohm
{#
Ternary Statements: Ternaries evaluate the variable
based on whether it is truthful
#}
{{ foo ? 'yes' : 'no' }} {# Returns 'yes' or 'no' #}
{{ foo ?: 'no' }} {# Returns foo or 'no' #}
{{ foo ? 'yes' }} {# Returns 'yes' or nothing #}
{#
Ternary Statements: Ternaries evaluate the variable
based on whether it is truthful
#}
{{ foo ?? 'no' }} {# Returns foo or 'no' #}
{# Difference in variable evaluation #}
{{ '' ?: 'no' }} {# Returns 'no' (because '' is falsey) #}
{{ '' ?? 'no' }} {# Returns '' (because '' is defined and not null) #}
{# Difference in handling undefined variables #}
{{ undefinedVar ?? 'fallback' }} {# Returns 'fallback' #}
{{ undefinedVar | default('fallback') }} {# Returns 'fallback' #}
{{ undefinedVar ?: 'fallback' }} {# Throws 'undefinedVar' does not exist (error) #}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment