Using Django Generics with Jinja2

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

#

(Forgotten your password?)