开发者

Django setting for default template tag output when variable is None?

I am looking for a django setting or programmatic way to make all django template tags show the empty string when the value is None. For example, imagine that I have some django template:

{{cat}} chases {{mouse}}

if both cat and mouse are None, it will render as:

None chases None

I am aware that I can set each one using {{cat|default:""}} or {{mouse|default_if_none:""}}

However, I am looking for some sort of开发者_如何学Go setting that would allow me to set the default for all tags, without explicitly adding |default:"" to every tag.

I am also aware of a setting called TEMPLATE_STRING_IF_INVALID. However, this setting applies only to invalid strings. None is considered valid.


No such thing exists. That's why the default and default_if_none filters exist. This is a feature; it makes you think about what you're doing instead of relying on some behavior that would often times be misleading. If there's a potential for a variable to be None, then you should plan for that contingency. If the variable should always have some value, then the "None" indicates something is not right. If the default was to just render a blank string, then you would not know whether the value is not defined or is actually a blank string. Write coherent code and forget about shortcuts.


"Explicit is better than implicit"

Think of how enraged you would be when things wouldn't render properly because you forgot that you had enabled the magic "render everything with a false value as a null string" setting.

If you find you're using the default_if_none filter a lot, you might want to consider changing casting None to '' BEFORE it's passed to the template.

Your template will be simpler, and you will have explicitly made this decision to stringify null values.


This should do the trick, put it somewhere in the initialization code, for eg. in wsgi.py

# Patch template Variable to output empty string for None values
from django.template.base import Variable
_resolve_lookup = Variable._resolve_lookup
def new_resolve_lookup(self, *args, **kwargs):
    o = _resolve_lookup(self, *args, **kwargs)
    return o or u""
Variable._resolve_lookup = new_resolve_lookup
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜