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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
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.
#
Thanks. I'll change it now (and use Context instead of RequestContext, too)
#
Please login first before commenting.