How to make Django template raise an error if a variable is missing in context

后端 未结 2 396
时光说笑
时光说笑 2021-01-01 10:45

I\'m using Django templates in a non-Django project and I want to make sure that my templates contain no references to variables that are not in context and for that I need

2条回答
  •  时光取名叫无心
    2021-01-01 10:51

    There is a Django Snippet which provides a solution:

    # settings.py
    class InvalidVarException(object):
        def __mod__(self, missing):
            try:
                missing_str=unicode(missing)
            except:
                missing_str='Failed to create string representation'
            raise Exception('Unknown template variable %r %s' % (missing, missing_str))
        def __contains__(self, search):
            if search=='%s':
                return True
            return False
    
    TEMPLATE_DEBUG=True
    TEMPLATE_STRING_IF_INVALID = InvalidVarException()
    

提交回复
热议问题