How do I use Django templates without the rest of Django? How do I use Django templates without the rest of Django? python python

How do I use Django templates without the rest of Django?


The solution is simple. It's actually well documented, but not too easy to find. (I had to dig around -- it didn't come up when I tried a few different Google searches.)

The following code works:

>>> from django.template import Template, Context>>> from django.conf import settings>>> settings.configure()>>> t = Template('My name is {{ my_name }}.')>>> c = Context({'my_name': 'Daryl Spitzer'})>>> t.render(c)u'My name is Daryl Spitzer.'

See the Django documentation (linked above) for a description of some of the settings you may want to define (as keyword arguments to configure).


Jinja2 syntax is pretty much the same as Django's with very few differences, and you get a much more powerfull template engine, which also compiles your template to bytecode (FAST!).

I use it for templating, including in Django itself, and it is very good. You can also easily write extensions if some feature you want is missing.

Here is some demonstration of the code generation:

>>> import jinja2>>> print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True) from __future__ import divisionfrom jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_joinname = Nonedef root(context, environment=environment):    l_data = context.resolve('data')    t_1 = environment.filters['upper']    if 0: yield None    for l_row in l_data:        if 0: yield None        yield unicode(t_1(environment.getattr(l_row, 'name')))blocks = {}debug_info = '1=9'


Any particular reason you want to use Django's templates? Both Jinja and Genshi are, in my opinion, superior.


If you really want to, then see the Django documentation on settings.py. Especially the section "Using settings without setting DJANGO_SETTINGS_MODULE". Use something like this:

from django.conf import settingssettings.configure (FOO='bar') # Your settings go here