django1/django/template/loaders/eggs.py

37 lines
1.2 KiB
Python
Raw Normal View History

# Wrapper for loading templates from eggs via pkg_resources.resource_string.
2012-08-14 18:09:45 +08:00
from __future__ import unicode_literals
try:
from pkg_resources import resource_string
except ImportError:
resource_string = None
from django.apps import apps
2012-08-14 18:09:45 +08:00
from django.conf import settings
from django.template.base import TemplateDoesNotExist
2012-08-14 18:09:45 +08:00
from django.utils import six
from .base import Loader as BaseLoader
class Loader(BaseLoader):
is_usable = resource_string is not None
def load_template_source(self, template_name, template_dirs=None):
"""
Loads templates from Python eggs via pkg_resource.resource_string.
For every installed app, it tries to get the resource (app, template_name).
"""
if resource_string is not None:
pkg_name = 'templates/' + template_name
for app_config in apps.get_app_configs():
try:
resource = resource_string(app_config.name, pkg_name)
2012-08-14 18:09:45 +08:00
except Exception:
continue
if six.PY2:
2012-08-14 18:09:45 +08:00
resource = resource.decode(settings.FILE_CHARSET)
return (resource, 'egg:%s:%s' % (app_config.name, pkg_name))
raise TemplateDoesNotExist(template_name)