Login

monkey-patch django to use jinja2 templates for 404/500 pages and 3rd-party apps

Author:
brondsem
Posted:
March 13, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

smulloni (on March 16, 2009):

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.