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

前端 未结 3 821
南笙
南笙 2021-02-03 21:54

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

3条回答
  •  清酒与你
    2021-02-03 22:22

    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
    

提交回复
热议问题