Suppress "None" output as string in Jinja2

PythonJinja2

Python Problem Overview


How do I persuade Jinja2 to not print "None" when the value is None?

I have a number of entries in a dictionary and I would like to output everything in a single loop instead of having special cases for different keywords. If I have a value of None (the NoneType not the string) then the string "None" is inserted into the template rendering results.

Trying to suppress it using {{ value or '' }} works too well as it will replace the numeric value zero as well.

Do I need to filter the dictionary before passing it to Jinja2 for rendering?

Python Solutions


Solution 1 - Python

In new versions of Jinja2 (2.9+):

{{ value if value }}

In older versions of Jinja2 (prior to 2.9):

{{ value if value is not none }} works great.

if this raises an error about not having an else try using an else ..

{{ value if value is not none else '' }}

Solution 2 - Python

Another option is to use the finalize hook on the environment:

>>> import jinja2
>>> e = jinja2.Environment()
>>> e.from_string("{{ this }} / {{ that }}").render(this=0, that=None)
u'0 / None'

but:

>>> def my_finalize(thing):
...     return thing if thing is not None else ''
...
>>> e = jinja2.Environment(finalize=my_finalize)
>>> e.from_string("{{ this }} / {{ that }}").render(this=0, that=None)
u'0 / '

Solution 3 - Python

Default filter:

{{ value|default("", True) }}

Solution 4 - Python

According to this post from the Pocco Mailing List: https://groups.google.com/d/msg/pocoo-libs/SQ9ubo_Kamw/TadIdab9eN8J

Armin Ronacher (creater of Jinja2/Flask, etc...) recommends the following "pythonic" snippet:

{{ variable or 0 }} {{ variable or '' }}

The notion here being that once again, explicit is preferable to implicit.

Edit: The selected answer is definitely the correct one. I haven't really come across a situation where a template variable would be either a string or the numeric zero, so the above snippets might help reduce the code noise in the template.

Solution 5 - Python

A custom filter can solve the problem. Declare it like this:

def filter_suppress_none(val):
    if not val is None:
        return val
    else:
        return ''

Install it like this:

templating_environment.filters['sn'] = filter_suppress_none

Use it like this:

{{value|sn}}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSpaceghostView Question on Stackoverflow
Solution 1 - PythonJoran BeasleyView Answer on Stackoverflow
Solution 2 - PythonSingleNegationEliminationView Answer on Stackoverflow
Solution 3 - PythonsolarcView Answer on Stackoverflow
Solution 4 - PythonBrownbayView Answer on Stackoverflow
Solution 5 - PythonAlexVhrView Answer on Stackoverflow