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
Tags:
templates jinja2
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. integrated jinja2 which could use generic view ,my djangojinja2.py by jasongreen 5 years, 2 months ago
  2. Django 1.2+ template loader for Jinja2 by SimonSapin 4 years, 8 months ago
  3. Accessing Environment Variables in Templates by LorenDavie 6 years, 7 months ago
  4. Jinja2 integration + application specific functions/filters/tests by hasenj 6 years, 5 months ago
  5. jinja2 csrf_token extension by jasongreen 5 years, 2 months 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.