Translate Toolkit & Pootle

Tools to help you make your software local

User Tools


Using kid templates with Django

Creating the template directory

Let's place the kid templates under the directory templates, which is directly under the root of your Django application.

In settings.py, add templates to the list TEMPLATE_DIRS:

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    'templates',
)

Adding a helper method to display templates

import os
from os import path
import kid
from django.http import HttpResponse

# settings.py is in the root of our Django application's
# directory structure, so we can use path.dirname to
# find the root directory.
from odf_xliff import settings
root_dir = path.dirname(settings.__file__)

def find_template(relative_template_path):
    """Find the full path of the template whose relative path is
    'relative_template_path'."""

    for template_dir in settings.TEMPLATE_DIRS:
        full_template_path = path.join(root_dir, template_dir, relative_template_path)
        if path.exists(full_template_path):
            return full_template_path
    raise Exception('No template named %s found' % relative_template_path)

def render(relative_template_path, **template_vars):
    # Find the template at relative_template_path, get the
    # constructed kid template and pass template_vars
    # through...
    template = kid.Template(file = find_template(relative_template_path), **template_vars)
    # Render the template to a string and send the string
    # to HttpResponse
    return HttpResponse(template.serialize())

Using the code

In the above code, since we only have the directory 'templates' in settings.TEMPLATE_DIRS, the file start.kid must appear at templates/start.kid. pagetitle is a template variable.

import template

def show_front(request):
    return template.render('start.kid', pagetitle=':)')

That's it. Django makes it easy to use your templating engine of choice.