Django Template Internals

Welcome and My gratitude for your patience and time.

After a long time came to write by cut off 1 episode of prison break.

Yesterday in my office we had a short discussion about django template system. Thanks to @shanmuganandhg and @rosarioarun

Template system Basics

Django template is one of the important component in django. Here We are not covering about Django template basics. But,we direct you here

Straight to the topic,

Once we got request, we process it, eventually response will be returned. So, mostly we use render_to_response shortcut method to return response in django views.


from django.shortcuts import render_to_response

return render_to_response(template, {}, context_instance=RequestContext(request))

digging render_to_response,

It takes three arguments(2 positional + 1 keyword arg),

1.template name 2. dictionary 3. RequestContext (optional).

The RequestContext is important when you need meta information in application like session key, login credentials etc..

render_to_response does nothing except calling render_to_string, so,

digging render_to_string,

It takes three arguments(2 positional + 1 keyword arg),

1.template name 2. dictionary 3. RequestContext (optional).

It is loading the template from loaders using the function called “find_template”

There are different type of template loaders are there.

loading from filesystem( ‘django.template.loaders.filesystem.Loader’,)

loading from cache etc…

you can write your own custom loader too.

How template content loading from loader?

It fetches the template loaders which defined at settings.TEMPLATE_LOADERS and passing the template name to the each loaders, finally receives the template content


 in this above attached image(taken from django source code) variable source is just template content in string format.

Now you got the template content as basestring. Here after compilation and rendering steps are there.

Get the template content as compiled.


t = Template(*args, **kwargs)

The template class is used to compile the raw template content with some functionalities.

Ok. So, What is happening in the Template class?


lexical analysis:                     

lexer = lexer_class(template_string, origin)


parser = parser_class(lexer.tokenize())

nodelist = parser.parse()

then returning the compiled template object.

rendering the compiled template with context dictionary

The compiled template which is splitted by token and parsing the tokens finally returning the evaluated tokens to be renders as html


Sample Workflow:

from django.template.base import Lexer,Parser

>>>template_string = """<html><title>
{% if flag %}
 Welcome to Python!!! 
{% else %} 
 Welcome to Django!! 
{% endif %}

>>>lexical_token = Lexer(template_string,{})
>>>print lexical_token
<django.template.base.Lexer at 0xabcb30c>

#parsing the nodes
>>>parser = Parser(lexical_token.tokenize())
>>>parsed = parser.parse()
>>>print parsed
[<Text Node: '<html><title>'>, <IfNode>, <Text Node: '</title></html>'>]

#Template is compiled,It is about to render now


TypeError Traceback (most recent call last)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <module>()
—-> 1 parsed.render()

>>>context = {}
#Rendered with else condition
 u'<html><title> Welcome to Django!! </title></html>'

>>>context = {"flag":True}
#Rendered with if condition
u'<html><title>Welcome to Python!!! </title></html>'

Post your views as comments. Sharing is learning !!


About Navaneethan

mixed feelings...
This entry was posted in Django, template and tagged , , , . Bookmark the permalink.

One Response to Django Template Internals

  1. He deeply looked into inside the django code. its great.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s