|
1 """ |
|
2 Wrapper class that takes a list of template loaders as an argument and attempts |
|
3 to load templates from them in order, caching the result. |
|
4 """ |
|
5 |
|
6 from django.template import TemplateDoesNotExist |
|
7 from django.template.loader import BaseLoader, get_template_from_string, find_template_loader, make_origin |
|
8 from django.utils.importlib import import_module |
|
9 from django.core.exceptions import ImproperlyConfigured |
|
10 |
|
11 class Loader(BaseLoader): |
|
12 is_usable = True |
|
13 |
|
14 def __init__(self, loaders): |
|
15 self.template_cache = {} |
|
16 self._loaders = loaders |
|
17 self._cached_loaders = [] |
|
18 |
|
19 @property |
|
20 def loaders(self): |
|
21 # Resolve loaders on demand to avoid circular imports |
|
22 if not self._cached_loaders: |
|
23 for loader in self._loaders: |
|
24 self._cached_loaders.append(find_template_loader(loader)) |
|
25 return self._cached_loaders |
|
26 |
|
27 def find_template(self, name, dirs=None): |
|
28 for loader in self.loaders: |
|
29 try: |
|
30 template, display_name = loader(name, dirs) |
|
31 return (template, make_origin(display_name, loader, name, dirs)) |
|
32 except TemplateDoesNotExist: |
|
33 pass |
|
34 raise TemplateDoesNotExist(name) |
|
35 |
|
36 def load_template(self, template_name, template_dirs=None): |
|
37 if template_name not in self.template_cache: |
|
38 template, origin = self.find_template(template_name, template_dirs) |
|
39 if not hasattr(template, 'render'): |
|
40 try: |
|
41 template = get_template_from_string(template, origin, template_name) |
|
42 except TemplateDoesNotExist: |
|
43 # If compiling the template we found raises TemplateDoesNotExist, |
|
44 # back off to returning the source and display name for the template |
|
45 # we were asked to load. This allows for correct identification (later) |
|
46 # of the actual template that does not exist. |
|
47 return template, origin |
|
48 self.template_cache[template_name] = template |
|
49 return self.template_cache[template_name], None |
|
50 |
|
51 def reset(self): |
|
52 "Empty the template cache." |
|
53 self.template_cache.clear() |