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 Django template renderer to raise an error when it sees {{ non_existent_variable }}
when there is no non_existent_variable
in Context.
TEMPLATE_STRING_IF_INVALID
could be set to something and then we could check that this something is not in the rendered template, but that is not elegant at all.
Can I somehow without too much work override the way Context swallows missing key errors?
If you use a variable that doesn't exist, the template system will insert the value of the string_if_invalid option, which is set to '' (the empty string) by default.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
POST form (your current approach)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With