Skip to content

Instantly share code, notes, and snippets.

@chumaumenze
Forked from Suor/jinjalink_loader.py
Created July 17, 2018 18:34
Show Gist options
  • Save chumaumenze/6391c4567ec518c3592828a647d8d1b9 to your computer and use it in GitHub Desktop.
Save chumaumenze/6391c4567ec518c3592828a647d8d1b9 to your computer and use it in GitHub Desktop.
Jinja2 template loader for django
...
# 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,
}
# 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})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment