Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress "None" output as string in Jinja2

Tags:

python

jinja2

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?

like image 903
Spaceghost Avatar asked Jun 21 '12 20:06

Spaceghost


2 Answers

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 '' }}

like image 80
Joran Beasley Avatar answered Oct 09 '22 16:10

Joran Beasley


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 / ' 
like image 45
SingleNegationElimination Avatar answered Oct 09 '22 17:10

SingleNegationElimination