Created
March 17, 2019 23:25
-
-
Save sergeifilippov/0378c7c20b383c4edc13869730675ee1 to your computer and use it in GitHub Desktop.
How Twig ternary statements work by John Dohm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# | |
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