A nerd pretending to be a software engineer.

Django Template System

Written on

Okay, last time I talked about the basic web page in Django, and it used the shortest shortcut with the render_to_reponse, but there are manual way to do the same thing using Template and Context class, and there are many scenario where we might want to do it the manual way to have more control, so to do it manually, here is the code:

from django.http import HttpResponse
from django.template import Context,Template
from django.template.loader import get_template

def index(request):
    """Here is how to do it manually"""
    # load the raw template string to the variable,
    # you can also manually define the string in the same file,
    # but that wouldn't be very maintainable, but it is basically
    # an ordinary string
    t = get_template('index.html')
    c = Context({'title':'The Index Page','text':'Hello World!'})
    html = t.render(c)
    # return the http request, and pass html as the
    # body of the response
    return HttpResponse(html)

This entry is posted in 2012.

comments powered by Disqus