Login

Using Django Generics with Jinja2

Author:
rmt
Posted:
December 10, 2008
Language:
Python
Version:
1.0
Tags:
django jinja jinja2
Score:
1 (after 1 ratings)

Jinja2, while a great replacement for Django templates, is not a drop-in replacement for it. I wanted to use Photologue with my Jinja templates, but because Photologue uses Django generics, so I decided to see if I could use Jinja2 with generics, and then only modify the templates. It was a bit of work, but I seem to have done it. Django generics can take template_loader as an option, so if you have the same interface, things should just work.

The template must accept RequestContext as an argument to render(), so here we subclass jinja2.Template and when it receives Django's RequestContext object, it creates a flat dictionary from it, which jinja2 can work with.

 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
27
28
29
30
31
32
# This allows us to use Django's generics with Jinja2, by passing in
# 'template_loader' : jinjaenvironment as part of the dict

# in jinjasupport.py
from django.template.context import Context
import jinja2

class DjangoTemplate(jinja2.Template):
    def render(self, *args, **kwargs):
        if args and isinstance(args[0], Context):
            for d in reversed(args[0].dicts):
                kwargs.update(d)
            args = []
        return super(DjangoTemplate, self).render(*args, **kwargs)

class DjangoEnvironment(jinja2.Environment):
    template_class = DjangoTemplate

jenv = DjangoEnvironment(loader=FileSystemLoader(template_dirs))

# in urls.py - EXAMPLE ONLY
from jinjasupport import jenv

urlpatterns += patterns('django.views.generic.date_based',
  url(r'^photo/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[\-\d\w]+)/$',
      'object_detail',
      {
          'date_field' : 'date_added',
          'slug_field' : 'title_slug',
          'template_loader' : jinjasupport.jenv,
      }, name='pl-photo-detail'),
)

More like this

  1. Django 1.2+ template loader for Jinja2 by SimonSapin 5 years, 1 month ago
  2. Jinja2 integration + application specific functions/filters/tests by hasenj 6 years, 10 months ago
  3. monkey-patch django to use jinja2 templates for 404/500 pages and 3rd-party apps by brondsem 6 years, 4 months ago
  4. integrated jinja2 which could use generic view ,my djangojinja2.py by jasongreen 5 years, 7 months ago
  5. Jinja2 Django integration by mathwizard 6 years, 10 months ago

Comments

bretthoerner (on April 15, 2009):

Your context smashing in render is backwards, unless I'm missing something.

You're overwriting variables that were higher in the stack with ones that are lower. You need to do it in reverse or check for the existence of each variable before you smash it.

for d in reversed(args[0].dicts):
    kwargs.update(d)

#

rmt (on May 17, 2009):

Thanks. I'll change it now (and use Context instead of RequestContext, too)

#

Please login first before commenting.