Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 611
jbasko Avatar asked Mar 09 '13 15:03

jbasko


People also ask

What will insert template system in Django Temlates If you use a variable that doesn't exist?

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.

What does {% %} mean in Django?

{% %} 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.

What is a more efficient way to pass variables from template to view in Django?

POST form (your current approach)


1 Answers

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() 
like image 111
catherine Avatar answered Sep 22 '22 23:09

catherine