Skip to content

Instantly share code, notes, and snippets.

  • Select an option

Select an option

Revisions

  1. sergeifilippov created this gist Mar 17, 2019.
    26 changes: 26 additions & 0 deletions how-twig-ternary-statements-work.twig
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    {#
    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) #}