| 1 | | "Wrapper for loading templates from storage of some sort (e.g. files or db)" |
|---|
| 2 | | |
|---|
| | 1 | # Wrapper for loading templates from storage of some sort (e.g. filesystem, database). |
|---|
| | 2 | # |
|---|
| | 3 | # This uses the TEMPLATE_LOADERS setting, which is a list of loaders to use. |
|---|
| | 4 | # Each loader is expected to have this interface: |
|---|
| | 5 | # |
|---|
| | 6 | # callable(name, dirs=[]) |
|---|
| | 7 | # |
|---|
| | 8 | # name is the template name. |
|---|
| | 9 | # dirs is an optional list of directories to search instead of TEMPLATE_DIRS. |
|---|
| | 10 | # |
|---|
| | 11 | # Each loader should have an "is_usable" attribute set. This is a boolean that |
|---|
| | 12 | # specifies whether the loader can be used in this Python installation. Each |
|---|
| | 13 | # loader is responsible for setting this when it's initialized. |
|---|
| | 14 | # |
|---|
| | 15 | # For example, the eggs loader (which is capable of loading templates from |
|---|
| | 16 | # Python eggs) sets is_usable to False if the "pkg_resources" module isn't |
|---|
| | 17 | # installed, because pkg_resources is necessary to read eggs. |
|---|
| | 18 | |
|---|
| | 19 | from django.core.exceptions import ImproperlyConfigured |
|---|
| 4 | | from django.core.template.loaders.filesystem import load_template_source |
|---|
| | 21 | from django.conf.settings import TEMPLATE_LOADERS |
|---|
| | 22 | |
|---|
| | 23 | template_source_loaders = [] |
|---|
| | 24 | for path in TEMPLATE_LOADERS: |
|---|
| | 25 | i = path.rfind('.') |
|---|
| | 26 | module, attr = path[:i], path[i+1:] |
|---|
| | 27 | try: |
|---|
| | 28 | mod = __import__(module, globals(), locals(), [attr]) |
|---|
| | 29 | except ImportError, e: |
|---|
| | 30 | raise ImproperlyConfigured, 'Error importing template source loader %s: "%s"' % (module, e) |
|---|
| | 31 | try: |
|---|
| | 32 | func = getattr(mod, attr) |
|---|
| | 33 | except AttributeError: |
|---|
| | 34 | raise ImproperlyConfigured, 'Module "%s" does not define a "%s" callable template source loader' % (module, attr) |
|---|
| | 35 | if not func.is_usable: |
|---|
| | 36 | import warnings |
|---|
| | 37 | warnings.warn("Your TEMPLATE_LOADERS setting includes %r, but your Python installation doesn't support that type of template loading. Consider removing that line from TEMPLATE_LOADERS." % path) |
|---|
| | 38 | else: |
|---|
| | 39 | template_source_loaders.append(func) |
|---|
| | 40 | |
|---|
| | 41 | def load_template_source(name, dirs=None): |
|---|
| | 42 | for loader in template_source_loaders: |
|---|
| | 43 | try: |
|---|
| | 44 | return loader(name, dirs) |
|---|
| | 45 | except template.TemplateDoesNotExist: |
|---|
| | 46 | pass |
|---|
| | 47 | raise template.TemplateDoesNotExist, name |
|---|