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  https://docs.djangoproject.com/en/dev/topics/templates

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.

How?

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

find_template

 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.

How?

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?

compile_string()

lexical analysis:                     

lexer = lexer_class(template_string, origin)

Parsing:

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

t.render(context_dictionary)

Sample Workflow:

from django.template.base import Lexer,Parser

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

#Compilation
>>>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

>>>parsed.render()

parsed.render()
—————————————————————————
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
>>>parsed.render(context)
 u'<html><title> Welcome to Django!! </title></html>'

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

Post your views as comments. Sharing is learning !!

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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