This is heavily inspired by http://code.google.com/p/smorgasbord/. But that couldn't reuse an existing jinja2 Environment, nor set filters on the Environment it created.
This code assumes that you have env
declared previously in the file as your Jinja2 Environment instance.
In settings.py
, you should set
KEEP_DJANGO_TEMPLATES = (
'/django/contrib/',
)
so that your Django admin still works. You can also set any other places that you do want to use Django templates there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
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.
#
Please login first before commenting.