-
Notifications
You must be signed in to change notification settings - Fork 0
/
jinja2_for_django.py
60 lines (48 loc) · 2.03 KB
/
jinja2_for_django.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
See http://docs.djangoproject.com/en/dev/ref/templates/api/#using-an-alternative-template-language
Use:
* {{ url_for('view_name') }} instead of {% url view_name %},
* <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
instead of {% csrf_token %}.
"""
from django.template.loader import BaseLoader
#from django.template.loaders.app_directories import app_template_dirs
from django.template import TemplateDoesNotExist
from django.core import urlresolvers
from django.conf import settings
import jinja2
from app import jinja
class Template(jinja2.Template):
def render(self, context):
# flatten the Django Context into a single dictionary.
context_dict = {}
for d in context.dicts:
context_dict.update(d)
return super(Template, self).render(context_dict)
class Loader(BaseLoader):
is_usable = True
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(settings.TEMPLATE_DIRS),
autoescape=False,extensions=['jinja2.ext.autoescape'])
env.template_class = Template
# These are available to all templates.
env.globals['url_for'] = urlresolvers.reverse
env.globals['MEDIA_URL'] = settings.MEDIA_URL
env.globals['JQUERY_URL'] = settings.JQUERY_URL
#env.globals['STATIC_URL'] = settings.STATIC_URL
for fname in jinja.__all__:
env.globals[fname] = getattr(jinja, fname)
def format(value, format=settings.DATE_FORMAT):
from django.utils import dateformat
return dateformat.format(value, format)
def time_format(value, format=settings.TIME_FORMAT):
from django.utils import dateformat
return dateformat.time_format(value, format)
env.filters["date"] = format
env.filters["time"] = time_format
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