Monday, January 16, 2017

Django - 026 - How invalid variables are handled

Generally, if a variable does not exist, the template system inserts the value of the engine's string_if_invalid configuration option, which is an empty string by default. For example:

$ python manage.py shell -i python
Python 2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 17:02:03) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.template import Template,Context
>>> t = Template("Your name is {{name}}.")
>>> t.render(Context())
u'Your name is .'
>>> t.render(Context({'var':'Sandhya'}))
u'Your name is .'
>>> t.render(Context({'NAME':'Sandhya'}))
u'Your name is .'
>>> t.render(Context({'Name':'Sandhya'}))
u'Your name is .'
>>> 
This behavior is better than raising an exception because it is intended to be resilient to human error. In this case, all of the lookups failed because variable names have the wrong case or name. In the real world, it is unacceptable for a web site to become inaccessible due to a small template syntax error.

No comments:

Post a Comment