Created
November 29, 2011 12:13
-
-
Save bradwright/1404610 to your computer and use it in GitHub Desktop.
Django and Jinja together at last
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
djangojinja2 | |
~~~~~~~~~~~~ | |
Adds support for Jinja2 to Django. | |
Configuration variables: | |
======================= ============================================= | |
Key Description | |
======================= ============================================= | |
`JINJA2_TEMPLATE_DIRS` List of template folders | |
`JINJA2_EXTENSIONS` List of Jinja2 extensions to use | |
`JINJA2_CACHE_SIZE` The size of the Jinja2 template cache. | |
`JINJA2_GLOBAL_FUNCS` List of functions (as strings) to include. | |
`JINJA2_GLOBAL_FILTERS` List of filters (as string) to include. | |
======================= ============================================= | |
:copyright: (c) 2009 by the Jinja Team. | |
:license: BSD. | |
""" | |
from itertools import chain | |
from django.conf import settings | |
from django.http import HttpResponse | |
from django.template.loader import find_template_source | |
from django.template.context import get_standard_processors | |
from django.template import TemplateDoesNotExist | |
from django.utils.importlib import import_module | |
from jinja2 import Environment, FileSystemLoader, TemplateNotFound | |
# the environment is unconfigured until the first template is loaded. | |
_JINJA_ENV = None | |
def get_env(): | |
"""Get the Jinja2 env and initialize it if necessary.""" | |
global _JINJA_ENV | |
if _JINJA_ENV is None: | |
_JINJA_ENV = create_env() | |
return _JINJA_ENV | |
def import_attr(function): | |
"""Import a function/module attribute by string""" | |
dot = function.rindex('.') | |
att_module, att_name = function[:dot], function[dot+1:] | |
return getattr(import_module(att_module), att_name) | |
def create_env(): | |
"""Create a new Jinja2 environment.""" | |
searchpath = list(settings.JINJA2_TEMPLATE_DIRS) | |
env = Environment(loader=FileSystemLoader(searchpath), | |
auto_reload=settings.TEMPLATE_DEBUG, | |
cache_size=getattr(settings, 'JINJA2_CACHE_SIZE', 50), | |
extensions=getattr(settings, 'JINJA2_EXTENSIONS', ())) | |
# patch the environment to accept some global functions | |
if hasattr(settings, 'JINJA2_GLOBAL_FUNCS'): | |
env.globals['h'] = {} | |
for function in list(settings.JINJA2_GLOBAL_FUNCS): | |
function = import_attr(function) | |
env.globals['h'][function.func_name] = function | |
if hasattr(settings, 'JINJA2_GLOBAL_FILTERS'): | |
for function in list(settings.JINJA2_GLOBAL_FILTERS): | |
function = import_attr(function) | |
env.filters[function.func_name] = function | |
return env | |
def get_template(template_name, globals=None, request=None): | |
"""Load a template.""" | |
if request and 'jinja2.environment' in request.META: | |
env = request.META['jinja2.environment'] | |
else: | |
env = get_env() | |
try: | |
return env.get_template(template_name, globals=globals) | |
except TemplateNotFound, ex: | |
if settings.DEBUG: | |
# find a template we know exists to avoid white screen of death | |
find_template_source(template_name) | |
raise TemplateDoesNotExist(str(ex)) | |
def select_template(templates, globals=None, request=None): | |
"""Try to load one of the given templates.""" | |
if request and 'jinja2.environment' in request.META: | |
env = request.META['jinja2.environment'] | |
else: | |
env = get_env() | |
for template in templates: | |
try: | |
return env.get_template(template, globals=globals) | |
except TemplateNotFound: | |
continue | |
raise TemplateDoesNotExist(', '.join(templates)) | |
def render_to_string(template_name, context=None, request=None, | |
processors=None): | |
"""Render a template into a string.""" | |
context = dict(context or {}) | |
if request is not None: | |
with request.timed('context_processors'): | |
context['request'] = request | |
for processor in chain(get_standard_processors(), processors or ()): | |
context.update(processor(request)) | |
template = get_template(template_name, request=request) | |
return template.render(context) | |
def render_to_response(template_name, context=None, request=None, | |
processors=None, mimetype=None): | |
"""Render a template into a response object.""" | |
return HttpResponse(render_to_string(template_name, context, request, | |
processors), mimetype=mimetype) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# rest of settings here... | |
JINJA2_GLOBAL_FILTERS = [ | |
'django.template.defaultfilters.pluralize', | |
'django.template.defaultfilters.date', | |
'django.template.defaultfilters.urlencode', | |
'django.template.defaultfilters.truncatewords_html', | |
'django.contrib.humanize.templatetags.humanize.ordinal' | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from djangojinja2 import render_to_response, render_to_string | |
# rest of stuff | |
def my_view(request): | |
return render_to_response('my_view.jinja', {}, request) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment