filesystem.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """
  2. Wrapper for loading templates from the filesystem.
  3. """
  4. from django.conf import settings
  5. from django.template.base import TemplateDoesNotExist
  6. from django.template.loader import BaseLoader
  7. from django.utils._os import safe_join
  8. class Loader(BaseLoader):
  9. is_usable = True
  10. def get_template_sources(self, template_name, template_dirs=None):
  11. """
  12. Returns the absolute paths to "template_name", when appended to each
  13. directory in "template_dirs". Any paths that don't lie inside one of the
  14. template dirs are excluded from the result set, for security reasons.
  15. """
  16. if not template_dirs:
  17. template_dirs = settings.TEMPLATE_DIRS
  18. for template_dir in template_dirs:
  19. try:
  20. yield safe_join(template_dir, template_name)
  21. except UnicodeDecodeError:
  22. # The template dir name was a bytestring that wasn't valid UTF-8.
  23. raise
  24. except ValueError:
  25. # The joined path was located outside of this particular
  26. # template_dir (it might be inside another one, so this isn't
  27. # fatal).
  28. pass
  29. def load_template_source(self, template_name, template_dirs=None):
  30. tried = []
  31. for filepath in self.get_template_sources(template_name, template_dirs):
  32. try:
  33. with open(filepath, 'rb') as fp:
  34. return (fp.read().decode(settings.FILE_CHARSET), filepath)
  35. except IOError:
  36. tried.append(filepath)
  37. if tried:
  38. error_msg = "Tried %s" % tried
  39. else:
  40. error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory."
  41. raise TemplateDoesNotExist(error_msg)
  42. load_template_source.is_usable = True