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

 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 3 years, 4 months ago
  2. Django 1.2+ template loader for Jinja2 by SimonSapin 2 years, 11 months ago
  3. jinja2 csrf_token extension by jasongreen 3 years, 4 months ago
  4. A few jinja2 filters like django ones by brondsem 4 years, 2 months ago
  5. Jinja2 Django integration by mathwizard 4 years, 8 months ago

Comments

ericflo (on March 13, 2009):

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

#

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.

#

brondsem (on April 2, 2009):

@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

#

(Forgotten your password?)