public
Created

Jinja2 template loader for django

  • Download Gist
settings.py
Python
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 33 34 35 36 37 38 39 40 41 42 43 44 45
...
# First try to load with our loader then fallback to django default templates
# We should use another (not .html) extension for our Jinja2 templates in order to make this work
TEMPLATE_LOADERS = (
'jinjalink_loader.Loader',
# these loaders here for admin, contrib and third-party apps
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
# These settings work as you expect for both Jinja2 and Django templates
TEMPLATE_DIRS = (
HOME_DIR + '/templates'
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
)
 
# And these are for Jinja2 only
JINJA2_EXTENSIONS = (
'jinja2.ext.with_',
)
JINJA2_FILTERS = {
# use django filters in jinja
'floatformat': 'django.template.defaultfilters.floatformat',
'slugify': 'django.template.defaultfilters.slugify',
# add your custom ones here
...
}
# You can also just list them, function names will be used as filter names:
#JINJA2_FILTERS = ('django.template.defaultfilters.floatformat',
# 'django.template.defaultfilters.slugify')
 
# Used similar to filters
JINJA2_GLOBALS = {
'now': 'datetime.now',
}
JINJA2_TESTS = {}
# and add some options here
JINJA2_ENVIRONMENT_OPTIONS = {
'autoescape': True,
}
views.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13
# an example is borrowed from django tutorial
from django.shortcuts import render_to_response, get_object_or_404
 
# Using Django templates
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p})
 
# Using Jinja2 templates
# Any extension but ".html" will do. I simply like .j2
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.j2', {'poll': p})

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.