Django template standalone

When writing a python webserver, using django templates is an easy way to print HTML and have access to powerful functionalities.

You may want to use them standalone, without the whole django thing around though. Here are some useful snippet of code to achieve that.

You can also have a look at the custom tags and filters used in this example.

from django.conf import settings
settings.configure(TEMPLATE_DIRS=('templates',), DEBUG=False,
from django import template
from django.template import Template, loader, Context

def SetupDjangoFiltersAndTags():
  # See django doc on hwo to define your own tags and filters.
  # Here, imagine I have 2 tags and 1 filter: setvar, split and jsid.
  from templatetags import jsid, setvar, split
  register = template.Library()
  register.filter('jsid', jsid)
  register.tag('setvar', setvar)
  register.tag('split', split)
  # Then your template can use {{ "{{myVar|jsid"}}}}, or
  # {{ "{% setvar myVar newVar "}}%}...

And then, the usage part:

# In a BaseHTTPRequestHandler subclass for example:
def UseTemplate(self):
  self.send_header('Content-type', 'text/html')
  t = loader.get_template("mytemplate.html")
  group = {'var': 123, 'user': username}
  c = Context(group)


Django custom tags and filters » « Split a GPX file into tracks