loader.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. # The loader should return a tuple of (template_source, path). The path returned
  12. # might be shown to the user for debugging purposes, so it should identify where
  13. # the template was loaded from.
  14. #
  15. # A loader may return an already-compiled template instead of the actual
  16. # template source. In that case the path returned should be None, since the
  17. # path information is associated with the template during the compilation,
  18. # which has already been done.
  19. #
  20. # Each loader should have an "is_usable" attribute set. This is a boolean that
  21. # specifies whether the loader can be used in this Python installation. Each
  22. # loader is responsible for setting this when it's initialized.
  23. #
  24. # For example, the eggs loader (which is capable of loading templates from
  25. # Python eggs) sets is_usable to False if the "pkg_resources" module isn't
  26. # installed, because pkg_resources is necessary to read eggs.
  27. from django.core.exceptions import ImproperlyConfigured
  28. from django.template.base import Origin, Template, Context, TemplateDoesNotExist
  29. from django.conf import settings
  30. from django.utils.module_loading import import_string
  31. from django.utils import six
  32. template_source_loaders = None
  33. class BaseLoader(object):
  34. is_usable = False
  35. def __init__(self, *args, **kwargs):
  36. pass
  37. def __call__(self, template_name, template_dirs=None):
  38. return self.load_template(template_name, template_dirs)
  39. def load_template(self, template_name, template_dirs=None):
  40. source, display_name = self.load_template_source(template_name, template_dirs)
  41. origin = make_origin(display_name, self.load_template_source, template_name, template_dirs)
  42. try:
  43. template = get_template_from_string(source, origin, template_name)
  44. return template, None
  45. except TemplateDoesNotExist:
  46. # If compiling the template we found raises TemplateDoesNotExist, back off to
  47. # returning the source and display name for the template we were asked to load.
  48. # This allows for correct identification (later) of the actual template that does
  49. # not exist.
  50. return source, display_name
  51. def load_template_source(self, template_name, template_dirs=None):
  52. """
  53. Returns a tuple containing the source and origin for the given template
  54. name.
  55. """
  56. raise NotImplementedError('subclasses of BaseLoader must provide a load_template_source() method')
  57. def reset(self):
  58. """
  59. Resets any state maintained by the loader instance (e.g., cached
  60. templates or cached loader modules).
  61. """
  62. pass
  63. class LoaderOrigin(Origin):
  64. def __init__(self, display_name, loader, name, dirs):
  65. super(LoaderOrigin, self).__init__(display_name)
  66. self.loader, self.loadname, self.dirs = loader, name, dirs
  67. def reload(self):
  68. return self.loader(self.loadname, self.dirs)[0]
  69. def make_origin(display_name, loader, name, dirs):
  70. if settings.TEMPLATE_DEBUG and display_name:
  71. return LoaderOrigin(display_name, loader, name, dirs)
  72. else:
  73. return None
  74. def find_template_loader(loader):
  75. if isinstance(loader, (tuple, list)):
  76. loader, args = loader[0], loader[1:]
  77. else:
  78. args = []
  79. if isinstance(loader, six.string_types):
  80. TemplateLoader = import_string(loader)
  81. if hasattr(TemplateLoader, 'load_template_source'):
  82. func = TemplateLoader(*args)
  83. else:
  84. # Try loading module the old way - string is full path to callable
  85. if args:
  86. raise ImproperlyConfigured("Error importing template source loader %s - can't pass arguments to function-based loader." % loader)
  87. func = TemplateLoader
  88. if not func.is_usable:
  89. import warnings
  90. 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." % loader)
  91. return None
  92. else:
  93. return func
  94. else:
  95. raise ImproperlyConfigured('Loader does not define a "load_template" callable template source loader')
  96. def find_template(name, dirs=None):
  97. # Calculate template_source_loaders the first time the function is executed
  98. # because putting this logic in the module-level namespace may cause
  99. # circular import errors. See Django ticket #1292.
  100. global template_source_loaders
  101. if template_source_loaders is None:
  102. loaders = []
  103. for loader_name in settings.TEMPLATE_LOADERS:
  104. loader = find_template_loader(loader_name)
  105. if loader is not None:
  106. loaders.append(loader)
  107. template_source_loaders = tuple(loaders)
  108. for loader in template_source_loaders:
  109. try:
  110. source, display_name = loader(name, dirs)
  111. return (source, make_origin(display_name, loader, name, dirs))
  112. except TemplateDoesNotExist:
  113. pass
  114. raise TemplateDoesNotExist(name)
  115. def get_template(template_name, dirs=None):
  116. """
  117. Returns a compiled Template object for the given template name,
  118. handling template inheritance recursively.
  119. """
  120. template, origin = find_template(template_name, dirs)
  121. if not hasattr(template, 'render'):
  122. # template needs to be compiled
  123. template = get_template_from_string(template, origin, template_name)
  124. return template
  125. def get_template_from_string(source, origin=None, name=None):
  126. """
  127. Returns a compiled Template object for the given template code,
  128. handling template inheritance recursively.
  129. """
  130. return Template(source, origin, name)
  131. def render_to_string(template_name, dictionary=None, context_instance=None,
  132. dirs=None):
  133. """
  134. Loads the given template_name and renders it with the given dictionary as
  135. context. The template_name may be a string to load a single template using
  136. get_template, or it may be a tuple to use select_template to find one of
  137. the templates in the list. Returns a string.
  138. """
  139. if isinstance(template_name, (list, tuple)):
  140. t = select_template(template_name, dirs)
  141. else:
  142. t = get_template(template_name, dirs)
  143. if not context_instance:
  144. return t.render(Context(dictionary))
  145. if not dictionary:
  146. return t.render(context_instance)
  147. # Add the dictionary to the context stack, ensuring it gets removed again
  148. # to keep the context_instance in the same state it started in.
  149. with context_instance.push(dictionary):
  150. return t.render(context_instance)
  151. def select_template(template_name_list, dirs=None):
  152. "Given a list of template names, returns the first that can be loaded."
  153. if not template_name_list:
  154. raise TemplateDoesNotExist("No template names provided")
  155. not_found = []
  156. for template_name in template_name_list:
  157. try:
  158. return get_template(template_name, dirs)
  159. except TemplateDoesNotExist as e:
  160. if e.args[0] not in not_found:
  161. not_found.append(e.args[0])
  162. continue
  163. # If we get here, none of the templates could be loaded
  164. raise TemplateDoesNotExist(', '.join(not_found))