Django view - load template from calling app's dir first

前端 未结 3 1342
甜味超标
甜味超标 2020-12-04 17:51

I try to keep a somewhat consistent naming scheme on my HTML templates. I.e. index.html for main, delete.html for delete page and so forth. But the app_directories

3条回答
  •  一向
    一向 (楼主)
    2020-12-04 18:42

    I know this is an old thread, but I made something reusable, that allows for simpler namespacing. You could load the following as a Template Loader. It will find appname/index.html in appname/templates/index.html.

    Gist available here: https://gist.github.com/871567

    """
    Wrapper for loading templates from "templates" directories in INSTALLED_APPS
    packages, prefixed by the appname for namespacing.
    
    This loader finds `appname/templates/index.html` when looking for something
    of the form `appname/index.html`.
    """
    
    from django.template import TemplateDoesNotExist
    from django.template.loaders.app_directories import app_template_dirs, Loader as BaseAppLoader
    
    class Loader(BaseAppLoader):
        '''
        Modified AppDirecotry Template Loader that allows namespacing templates
        with the name of their app, without requiring an extra subdirectory
        in the form of `appname/templates/appname`.
        '''
        def load_template_source(self, template_name, template_dirs=None):
            try:
                app_name, template_path = template_name.split('/', 1)
            except ValueError:
                raise TemplateDoesNotExist(template_name)
    
            if not template_dirs:
                template_dirs = (d for d in app_template_dirs if
                        d.endswith('/%s/templates' % app_name))
    
            return iter(super(Loader, self).load_template_source(template_path,
                    template_dirs))
    

提交回复
热议问题