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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
# -*- coding: utf-8 -*-
"""
djangojinja2
~~~~~~~~~~~~
Adds support for Jinja to Django.
Configuration variables:
======================= =============================================
Key Description
======================= =============================================
`JINJA2_TEMPLATE_DIRS` List of template folders
`JINJA2_EXTENSIONS` List of Jinja extensions to use
`JINJA2_CACHE_SIZE` The size of the Jinja template cache.
======================= =============================================
: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 import TemplateDoesNotExist
from django.template.context import get_standard_processors
from jinja2 import Environment
from jinja2 import FileSystemLoader
from jinja2 import TemplateNotFound
# the environment is unconfigured until the first template is loaded.
_jinja_env = None
def get_env():
"""Get the Jinja env and initialize it if necessary."""
global _jinja_env
if _jinja_env is None:
_jinja_env = create_env()
return _jinja_env
def create_env():
"""Create a new Jinja environment."""
searchpath = list(settings.JINJA2_TEMPLATE_DIRS)
return Environment(
loader=FileSystemLoader(searchpath),
auto_reload=settings.TEMPLATE_DEBUG,
cache_size=getattr(settings, "JINJA2_CACHE_SIZE", 400),
extensions=getattr(settings, "JINJA2_EXTENSIONS", ()),
)
def get_template(template_name, globals=None):
"""Load a template."""
try:
return get_env().get_template(template_name, globals=globals)
except TemplateNotFound as e:
raise TemplateDoesNotExist(str(e))
def select_template(templates, globals=None):
"""Try to load one of the given templates."""
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:
context["request"] = request
for processor in chain(get_standard_processors(), processors or ()):
context.update(processor(request))
return get_template(template_name).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
)
|