Sunday, May 18, 2008

Templates in Django

For a more comprehensive explanation about the templates system in django, please refer to: http://www.djangobook.com/en/beta/chapter04/. You'll be able to see the whole picture there. But just a quickie of how to do it, here's one way:

  1. Create the templates directory under your project directory
  2. Change settings.py to have that directory in the TEMPLATE_DIRS tupple. There are a few things to watch out for. First you have to put in the absolute path and not a relative path. If you want it to be more flexible than just add `import os.path` at the top and use `os.path.join(os.path.dirname(__file__),'templates'),` for the TEMPLATE_DIRS tupple. Second is that TEMPLATE_DIRS is supposed to be a tupple and so you have to add a comma at the end of the element even if there is only 1 element.
  3. Then in your view file add `from django.template.loader import get_template` and `from django.tempate import Context` at the top of the file.
  4. In the function you want to display the template first load it up `t = get_template('index.html')` and then set the context you want to use for it `html = t.render(Context({'name':'abdullah','age':16}))` and then just spit it out `return HttpResponse(html)`
  5. And in the templates directory you created just now add the file `index.html`. Create any kind of html you want in it. You could probably even design it in some WYSIWYG editor. Use {{name}} and {{age}} to display the variables we've set in the context.
And that's basically it. There are of course a lot more to templating than just tag replacing. Check out the link given above.

0 comments: