Thursday, January 12, 2017

Django - 023 - Multiple Contexts, same template

Once you have a Template object, you can render multiple contexts through it. 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('Hello, {{name}}')
>>> print t.render(Context({'name' : 'Mahesh'}))
Hello, Mahesh
>>> print t.render(Context({'name' : 'Ganesh'}))
Hello, Ganesh
>>> print t.render(Context({'name' : 'Saraswati'}))
Hello, Saraswati
>>> 


Whenever you are using the same template source to render multiple contexts like this, it is more efficient to create the Template object once, and then call render() on it multiple times:

>>> #bad practice - template inside the for loop
>>> for name in ('Mahesh','Ganesh','Saraswati'):
...    t = Template('Hello, {{name}}')
...    t.render(Context({'name' : name}))
...
u'Hello, Mahesh'
u'Hello, Ganesh'
u'Hello, Saraswati'
>>> 

>>> #good practice - template outside the for loop
>>> t = Template('Hello, {{name}}')
>>> for name in ('Mahesh','Ganesh','Saraswati'):
...    print t.render(Context({'name' : name}))
... 
Hello, Mahesh
Hello, Ganesh
Hello, Saraswati
>>> 

Django's template parsing is quite fast. Behind the scenes, most of the parsing happens via a call to a single-regular expression. This is stark contrast to XML based template engines, which incur the overhead of an XML parser and tend to be orders of magnitude slower than Django's template rendering engine.

No comments:

Post a Comment