blob: c97b5bf808c0c0e4c89a357b11a71cb98364ed46 [file] [log] [blame]
Armin Ronacher07bc6842008-03-31 14:18:49 +02001# -*- coding: utf-8 -*-
2"""
Armin Ronacherbcb7c532008-04-11 16:30:34 +02003 jinja2.loaders
4 ~~~~~~~~~~~~~~
Armin Ronacher07bc6842008-03-31 14:18:49 +02005
6 Jinja loader classes.
7
Armin Ronacherbcb7c532008-04-11 16:30:34 +02008 :copyright: 2008 by Armin Ronacher.
Armin Ronacher07bc6842008-03-31 14:18:49 +02009 :license: BSD, see LICENSE for more details.
10"""
Armin Ronacherce677102008-08-17 19:43:22 +020011try:
12 from os import path
13except ImportError:
14 # support for iron python without standard library
15 from _ipysupport import path
Armin Ronacher63fd7982008-06-20 18:47:56 +020016try:
17 from hashlib import sha1
18except ImportError:
19 from sha import new as sha1
Armin Ronacherbcb7c532008-04-11 16:30:34 +020020from jinja2.exceptions import TemplateNotFound
Armin Ronacher814f6c22008-04-17 15:52:23 +020021from jinja2.utils import LRUCache
Armin Ronacherbcb7c532008-04-11 16:30:34 +020022
23
Armin Ronacher9a822052008-04-17 18:44:07 +020024def split_template_path(template):
25 """Split a path into segments and perform a sanity check. If it detects
26 '..' in the path it will raise a `TemplateNotFound` error.
27 """
28 pieces = []
29 for piece in template.split('/'):
30 if path.sep in piece \
31 or (path.altsep and path.altsep in piece) or \
32 piece == path.pardir:
33 raise TemplateNotFound(template)
Armin Ronacher58f351d2008-05-28 21:30:14 +020034 elif piece and piece != '.':
Armin Ronacher9a822052008-04-17 18:44:07 +020035 pieces.append(piece)
36 return pieces
37
38
Armin Ronacherbcb7c532008-04-11 16:30:34 +020039class BaseLoader(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +020040 """Baseclass for all loaders. Subclass this and override `get_source` to
Armin Ronacherd1342312008-04-28 12:20:12 +020041 implement a custom loading mechanism. The environment provides a
42 `get_template` method that calls the loader's `load` method to get the
43 :class:`Template` object.
Armin Ronacher814f6c22008-04-17 15:52:23 +020044
Armin Ronacherd1342312008-04-28 12:20:12 +020045 A very basic example for a loader that looks up templates on the file
46 system could look like this::
47
48 from jinja2 import BaseLoader, TemplateNotFound
49 from os.path import join, exists, getmtime
50
51 class MyLoader(BaseLoader):
52
Armin Ronacher63fd7982008-06-20 18:47:56 +020053 def __init__(self, path):
Armin Ronacherd1342312008-04-28 12:20:12 +020054 self.path = path
55
56 def get_source(self, environment, template):
57 path = join(self.path, template)
58 if not exists(path):
59 raise TemplateNotFound(template)
60 mtime = getmtime(path)
61 with file(path) as f:
62 source = f.read().decode('utf-8')
Armin Ronacher4dc95782008-05-04 01:11:14 +020063 return source, path, lambda: mtime == getmtime(path)
Armin Ronacher814f6c22008-04-17 15:52:23 +020064 """
65
Armin Ronacherbcb7c532008-04-11 16:30:34 +020066 def get_source(self, environment, template):
Armin Ronacher814f6c22008-04-17 15:52:23 +020067 """Get the template source, filename and reload helper for a template.
68 It's passed the environment and template name and has to return a
69 tuple in the form ``(source, filename, uptodate)`` or raise a
70 `TemplateNotFound` error if it can't locate the template.
71
72 The source part of the returned tuple must be the source of the
73 template as unicode string or a ASCII bytestring. The filename should
74 be the name of the file on the filesystem if it was loaded from there,
75 otherwise `None`. The filename is used by python for the tracebacks
76 if no loader extension is used.
77
78 The last item in the tuple is the `uptodate` function. If auto
79 reloading is enabled it's always called to check if the template
80 changed. No arguments are passed so the function must store the
81 old state somewhere (for example in a closure). If it returns `False`
82 the template will be reloaded.
83 """
84 raise TemplateNotFound(template)
Armin Ronacherbcb7c532008-04-11 16:30:34 +020085
Armin Ronacherba3757b2008-04-16 19:43:16 +020086 def load(self, environment, name, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +020087 """Loads a template. This method looks up the template in the cache
88 or loads one by calling :meth:`get_source`. Subclasses should not
89 override this method as loaders working on collections of other
90 loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
91 will not call this method but `get_source` directly.
Armin Ronacher814f6c22008-04-17 15:52:23 +020092 """
93 if globals is None:
94 globals = {}
Armin Ronacher814f6c22008-04-17 15:52:23 +020095 source, filename, uptodate = self.get_source(environment, name)
Armin Ronacher981cbf62008-05-13 09:12:27 +020096 code = environment.compile(source, name, filename)
Armin Ronacher7259c762008-04-30 13:03:59 +020097 return environment.template_class.from_code(environment, code,
98 globals, uptodate)
Armin Ronacherbcb7c532008-04-11 16:30:34 +020099
100
101class FileSystemLoader(BaseLoader):
Armin Ronacherd1342312008-04-28 12:20:12 +0200102 """Loads templates from the file system. This loader can find templates
103 in folders on the file system and is the preferred way to load them.
104
105 The loader takes the path to the templates as string, or if multiple
106 locations are wanted a list of them which is then looked up in the
107 given order:
108
109 >>> loader = FileSystemLoader('/path/to/templates')
110 >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])
111
112 Per default the template encoding is ``'utf-8'`` which can be changed
113 by setting the `encoding` parameter to something else.
114 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200115
Armin Ronacher7259c762008-04-30 13:03:59 +0200116 def __init__(self, searchpath, encoding='utf-8'):
Armin Ronacher814f6c22008-04-17 15:52:23 +0200117 if isinstance(searchpath, basestring):
118 searchpath = [searchpath]
Armin Ronacherd1342312008-04-28 12:20:12 +0200119 self.searchpath = list(searchpath)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200120 self.encoding = encoding
121
122 def get_source(self, environment, template):
Armin Ronacher9a822052008-04-17 18:44:07 +0200123 pieces = split_template_path(template)
Armin Ronacher814f6c22008-04-17 15:52:23 +0200124 for searchpath in self.searchpath:
125 filename = path.join(searchpath, *pieces)
Armin Ronacher9a822052008-04-17 18:44:07 +0200126 if not path.isfile(filename):
127 continue
128 f = file(filename)
129 try:
130 contents = f.read().decode(self.encoding)
131 finally:
132 f.close()
133 old = path.getmtime(filename)
Armin Ronacher4dc95782008-05-04 01:11:14 +0200134 return contents, filename, lambda: path.getmtime(filename) == old
Armin Ronacher814f6c22008-04-17 15:52:23 +0200135 raise TemplateNotFound(template)
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200136
137
Armin Ronacher9a822052008-04-17 18:44:07 +0200138class PackageLoader(BaseLoader):
Armin Ronacherd1342312008-04-28 12:20:12 +0200139 """Load templates from python eggs or packages. It is constructed with
140 the name of the python package and the path to the templates in that
141 package:
Armin Ronacher9a822052008-04-17 18:44:07 +0200142
Armin Ronacherd1342312008-04-28 12:20:12 +0200143 >>> loader = PackageLoader('mypackage', 'views')
144
145 If the package path is not given, ``'templates'`` is assumed.
146
147 Per default the template encoding is ``'utf-8'`` which can be changed
148 by setting the `encoding` parameter to something else. Due to the nature
149 of eggs it's only possible to reload templates if the package was loaded
150 from the file system and not a zip file.
151 """
152
153 def __init__(self, package_name, package_path='templates',
Armin Ronacher7259c762008-04-30 13:03:59 +0200154 encoding='utf-8'):
Armin Ronacherd1342312008-04-28 12:20:12 +0200155 from pkg_resources import DefaultProvider, ResourceManager, get_provider
156 provider = get_provider(package_name)
157 self.encoding = encoding
158 self.manager = ResourceManager()
159 self.filesystem_bound = isinstance(provider, DefaultProvider)
160 self.provider = provider
Armin Ronacher9a822052008-04-17 18:44:07 +0200161 self.package_path = package_path
162
163 def get_source(self, environment, template):
Armin Ronacher963f97d2008-04-25 11:44:59 +0200164 pieces = split_template_path(template)
Armin Ronacherd1342312008-04-28 12:20:12 +0200165 p = '/'.join((self.package_path,) + tuple(pieces))
166 if not self.provider.has_resource(p):
Armin Ronacher9a822052008-04-17 18:44:07 +0200167 raise TemplateNotFound(template)
Armin Ronacherd1342312008-04-28 12:20:12 +0200168
169 filename = uptodate = None
170 if self.filesystem_bound:
171 filename = self.provider.get_resource_filename(self.manager, p)
172 mtime = path.getmtime(filename)
173 def uptodate():
Armin Ronacher4dc95782008-05-04 01:11:14 +0200174 return path.getmtime(filename) == mtime
Armin Ronacherd1342312008-04-28 12:20:12 +0200175
176 source = self.provider.get_resource_string(self.manager, p)
177 return source.decode(self.encoding), filename, uptodate
Armin Ronacher9a822052008-04-17 18:44:07 +0200178
179
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200180class DictLoader(BaseLoader):
Armin Ronacherd1342312008-04-28 12:20:12 +0200181 """Loads a template from a python dict. It's passed a dict of unicode
182 strings bound to template names. This loader is useful for unittesting:
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200183
Armin Ronacherd1342312008-04-28 12:20:12 +0200184 >>> loader = DictLoader({'index.html': 'source here'})
185
186 Because auto reloading is rarely useful this is disabled per default.
187 """
188
Armin Ronacher7259c762008-04-30 13:03:59 +0200189 def __init__(self, mapping):
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200190 self.mapping = mapping
191
192 def get_source(self, environment, template):
193 if template in self.mapping:
Armin Ronacherd1342312008-04-28 12:20:12 +0200194 source = self.mapping[template]
195 return source, None, lambda: source != self.mapping[template]
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200196 raise TemplateNotFound(template)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200197
198
199class FunctionLoader(BaseLoader):
200 """A loader that is passed a function which does the loading. The
Armin Ronacher963f97d2008-04-25 11:44:59 +0200201 function becomes the name of the template passed and has to return either
202 an unicode string with the template source, a tuple in the form ``(source,
203 filename, uptodatefunc)`` or `None` if the template does not exist.
Armin Ronacherd1342312008-04-28 12:20:12 +0200204
205 >>> def load_template(name):
206 ... if name == 'index.html'
207 ... return '...'
208 ...
209 >>> loader = FunctionLoader(load_template)
210
211 The `uptodatefunc` is a function that is called if autoreload is enabled
212 and has to return `True` if the template is still up to date. For more
213 details have a look at :meth:`BaseLoader.get_source` which has the same
214 return value.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200215 """
216
Armin Ronacher7259c762008-04-30 13:03:59 +0200217 def __init__(self, load_func):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200218 self.load_func = load_func
219
220 def get_source(self, environment, template):
Armin Ronacher963f97d2008-04-25 11:44:59 +0200221 rv = self.load_func(template)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200222 if rv is None:
223 raise TemplateNotFound(template)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200224 elif isinstance(rv, basestring):
225 return rv, None, None
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200226 return rv
227
228
229class PrefixLoader(BaseLoader):
230 """A loader that is passed a dict of loaders where each loader is bound
Armin Ronacher7259c762008-04-30 13:03:59 +0200231 to a prefix. The prefix is delimited from the template by a slash per
232 default, which can be changed by setting the `delimiter` argument to
233 something else.
Armin Ronacherd1342312008-04-28 12:20:12 +0200234
235 >>> loader = PrefixLoader({
236 ... 'app1': PackageLoader('mypackage.app1'),
237 ... 'app2': PackageLoader('mypackage.app2')
238 ... })
239
240 By loading ``'app1/index.html'`` the file from the app1 package is loaded,
241 by loading ``'app2/index.html'`` the file from the second.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200242 """
243
Armin Ronacher7259c762008-04-30 13:03:59 +0200244 def __init__(self, mapping, delimiter='/'):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200245 self.mapping = mapping
246 self.delimiter = delimiter
247
248 def get_source(self, environment, template):
249 try:
250 prefix, template = template.split(self.delimiter, 1)
251 loader = self.mapping[prefix]
252 except (ValueError, KeyError):
253 raise TemplateNotFound(template)
254 return loader.get_source(environment, template)
255
256
257class ChoiceLoader(BaseLoader):
258 """This loader works like the `PrefixLoader` just that no prefix is
259 specified. If a template could not be found by one loader the next one
Armin Ronacher7259c762008-04-30 13:03:59 +0200260 is tried.
Armin Ronacherd1342312008-04-28 12:20:12 +0200261
262 >>> loader = ChoiceLoader([
263 ... FileSystemLoader('/path/to/user/templates'),
Armin Ronacherabd36572008-06-27 08:45:19 +0200264 ... PackageLoader('mypackage')
Armin Ronacher61a5a242008-05-26 12:07:44 +0200265 ... ])
Armin Ronacherd1342312008-04-28 12:20:12 +0200266
267 This is useful if you want to allow users to override builtin templates
268 from a different location.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200269 """
270
Armin Ronacher7259c762008-04-30 13:03:59 +0200271 def __init__(self, loaders):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200272 self.loaders = loaders
273
274 def get_source(self, environment, template):
275 for loader in self.loaders:
276 try:
277 return loader.get_source(environment, template)
278 except TemplateNotFound:
279 pass
280 raise TemplateNotFound(template)