import django.template.loader as djloader
from django.template.loader import get_template as _original_get_template
def context_to_dict(ctxt):
res={}
for d in reversed(ctxt.dicts):
res.update(d)
return res
class Jinja2Template(object):
def __init__(self, template_obj):
self.template_obj=template_obj
def render(self, context):
return self.template_obj.render(context_to_dict(context))
def get_template(template_name):
source, origin = djloader.find_template_source(template_name) #, dirs
#logging.debug(origin.name)
for skip_path in getattr(settings, 'KEEP_DJANGO_TEMPLATES', ()):
if skip_path in origin.name:
return _original_get_template(template_name)
template = env.from_string(source)
template.name = template_name
return Jinja2Template(template)
djloader.get_template = get_template
Comments
The better solution is to write your own 404 and 500 handlers, as documented here: http://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
#
Actually, the jinja2 support code in smorgasbord does allow you to customize the jinja2 environment -- just define JINJA2_TEMPLATE_OPTS in settings, and they'll be passed to the Environment constructor. However, it does currently create a new Environment object with each invocation. Patches to support reusing an existing Environment, or caching one, would be welcome (and quite trivial).
And Eric, yes, that is true for 404/500 handlers, but the larger purpose here is to substitute jinja2 for django templates for 3rd party apps, a hack worthy in my view both of the raised eyebrow of suspicion and the raised dimple of delight.
#
@smulloni as far as I could tell you can't set filters on an Environment in it's constructor. You have to set the 'filters' attribute afterwards. See http://jinja.pocoo.org/2/documentation/api#high-level-api
#