Created
September 28, 2011 11:47
-
-
Save kesor/1247754 to your computer and use it in GitHub Desktop.
Django Jinja2 Loader
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
import jinja2 | |
from django.template.loader import BaseLoader | |
from django.template.loaders.app_directories import app_template_dirs | |
from django.template import TemplateDoesNotExist, Origin | |
from django.core import urlresolvers | |
from django.conf import settings | |
import datetime | |
import urllib | |
from django.utils.timesince import timesince, timeuntil | |
def yesno_filter(value, yes, no): | |
return yes if value else no | |
def timesince_filter(value): | |
return timsince(value, datatime.datetime.now()) | |
def timeuntil_filter(value): | |
return timeuntil(value, datetime.datetime.now()) | |
class Template(jinja2.Template): | |
def render(self, context): | |
# flatten Django Context into a single dictionary | |
context_dict = {} | |
map(context_dict.update, context) | |
if settings.TEMPLATE_DEBUG: | |
# when testing views django.test.client | |
# needs these extra signals sent to it | |
from django.test import signals | |
self.origin = Origin(self.filename) | |
signals.template_rendered.send( | |
sender=self, template=self, context=context) | |
return super(Template, self).render(context_dict) | |
class Loader(BaseLoader): | |
def __init__(self): | |
super(Loader, self).__init__() | |
self.is_usable = True | |
self.env = jinja2.Environment( | |
loader = jinja2.ChoiceLoader([jinja2.FileSystemLoader(path) \ | |
for path in settings.JINJA2_TEMPLATE_DIRS]), | |
# loader = jinja2.FileSystemLoader(app_template_dirs), | |
trim_blocks = True, | |
auto_reload = settings.DEBUG, | |
) | |
self.env.template_class = Template | |
self.env.filters.update(dict( | |
yesno = yesno_filter, | |
timesince = timesince_filter, | |
timeuntil = timeuntil_filter, | |
urlencode = urllib.urlencode, | |
)) | |
self.env.undefined = jinja2.StrictUndefined | |
if settings.DEBUG or settings.TEMPLATE_DEBUG: | |
self.env.undefined = jinja2.DebugUndefined | |
def load_template(self, template_name, template_dirs=None): | |
try: | |
template = self.env.get_template(template_name) | |
except jinja2.TemplateNotFound: | |
raise TemplateDoesNotExist(template_name) | |
return template, template.filename | |
def load_template_source(self, template_name, template_dirs=None): | |
try: | |
source, filename, uptodate = \ | |
self.env.loader.get_source(self.env, template_name) | |
except jinja2.TemplateNotFound: | |
raise TemplateDoesNotExist(template_name) | |
return source, filename |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment