Search code examples
djangodjango-templates

Does default_if_none have any use in Django templates?


From the Django docs,

Generally, if a variable doesn't exist, the template system inserts the value of the TEMPLATE_STRING_IF_INVALID setting, which is set to '' (the empty string) by default.

Filters that are applied to an invalid variable will only be applied if TEMPLATE_STRING_IF_INVALID is set to '' (the empty string). If TEMPLATE_STRING_IF_INVALID is set to any other value, variable filters will be ignored.

This behavior is slightly different for the if, for and regroup template tags. If an invalid variable is provided to one of these template tags, the variable will be interpreted as None. Filters are always applied to invalid variables within these template tags.

If an invalid variable always gets translated to '', for template tags and filters other than if, for and regroup, then what good does the template filter default_if_none do? Obsolete?


Solution

  • There is a difference between an invalid variable and one that exists but has a value of None.

    Consider the following context:

    {'apple':'green','banana':None}`
    

    In your template {{ apple }} resolves to green, while {{ banana }} resolves to None, and {{ orange }} resolves to TEMPLATE_STRING_IF_INVALID.

    Now consider {{ banana|default_if_none:'yellow' }} and you should see the use of the default_if_none tag.