Suppress "None" output as string in Jinja2
Solution 1:
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:
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:
Default filter:
{{ value|default("", True) }}