Python django 模板显示项目值或空字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16459890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
django template display item value or empty string
提问by Roger Liu
My code in template is like this:
我在模板中的代码是这样的:
{% for item in items %}
{{ item.somefield }}
{% endfor %}
I want to display the item value if the item.somefield is not None, or display an empty string. I don't want to use the {% if item.somefield %} statement, I want something like {{ item.somefield or '' }}(I tried this but it doesn't work)
如果 item.somefield 不是 None ,我想显示项目值,或者显示一个空字符串。我不想使用 {% if item.somefield %} 语句,我想要类似 {{ item.somefield 或 '' }} (我试过这个但它不起作用)
采纳答案by rockingskier
You want the default_if_nonetemplate filter, (doc).
您需要default_if_none模板过滤器 ( doc)。
default_if_nonewill display the given string if the variable is 'None'.
default_if_none如果变量为“无”,将显示给定的字符串。
defaultwill display the string if the variable evaluates to False, ie empty strings, empty lists etc
default如果变量的计算结果为 False,则将显示字符串,即空字符串、空列表等
{{ item.somefield|default_if_none:"" }}
{{ item.somefield|default:"" }}
回答by matino
{{ item.somefield|default_if_none:"" }}

