Skip to content

Instantly share code, notes, and snippets.

@rmax
Created June 13, 2010 16:50
Show Gist options
  • Save rmax/436800 to your computer and use it in GitHub Desktop.
Save rmax/436800 to your computer and use it in GitHub Desktop.
"""
Based on
http://www.bitbucket.org/mitsuhiko/jinja2-main/src/tip/ext/djangojinja2.py
"""
import jinja2
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.template import TemplateDoesNotExist
from django.template.loader import BaseLoader
class Template(jinja2.Template):
def render(self, context):
"""Flatten the Django Context object and calls Jinja's render"""
context_dict = {}
for d in context.dicts:
context_dict.update(d)
return super(Template, self).render(context_dict)
class Loader(BaseLoader):
is_usable = True
def __init__(self, *args, **kwargs):
super(Loader, self).__init__(*args, **kwargs)
try:
searchpath = list(settings.JINJA2_TEMPLATE_DIRS)
except AttributeError:
raise ImproperlyConfigured("Please fill out JINJA2_TEMPLATE_DIRS "
"in the settings module before using "
"this Jinja2 template loader")
self.env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath),
auto_reload=settings.TEMPLATE_DEBUG,
cache_size=getattr(settings, 'JINJA2_CACHE_SIZE', 50),
extensions=getattr(settings, 'JINJA2_EXTENSIONS', ()),
)
# use our custom Template class in this environment
self.env.template_class = Template
def load_template(self, template_name, template_dirs=None):
try:
# @@@: and template_dirs?
return self.env.get_template(template_name), None
except jinja2.TemplateNotFound, e:
raise TemplateDoesNotExist(str(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment