禁止“无"在Jinja2中输出为字符串 [英] Suppress "None" output as string in Jinja2
问题描述
当值None
时,如何说服Jinja2不打印"None"
?
How do I persuade Jinja2 to not print "None"
when the value is None
?
我在词典中有很多条目,我想在一个循环中输出所有内容,而不是针对不同的关键字使用特殊情况.如果我的值是None
(NoneType
不是字符串),则将字符串"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.
尝试使用抑制它
{{ value or '' }}
效果很好,因为它也会替换数字零.
Trying to suppress it using
{{ value or '' }}
works too well as it will replace the numeric value zero as well.
在将字典传递给Jinja2进行渲染之前,我是否需要过滤字典?
Do I need to filter the dictionary before passing it to Jinja2 for rendering?
推荐答案
在Jinja2(2.9+)的新版本中:
In new versions of Jinja2 (2.9+):
{{ value if value }}
在Jinja2的较早版本(2.9之前)中:
In older versions of Jinja2 (prior to 2.9):
{{ value if value is not none }}
效果很好.
如果这引起了关于没有其他的错误,请尝试使用else ..
if this raises an error about not having an else try using an else ..
{{ value if value is not none else '' }}
这篇关于禁止“无"在Jinja2中输出为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!