Typically, you store templates as files on the file system, but you can also use custom template loaders to load templates from other sources.
Django has two ways to load templates
- django.template.loader.get_template(template_name): get_template returns a compiled template (a Template object) based on the given template name. If the template does not exist, the TemplateDoesNotExist exception is triggered.
- django.template.loader.select_template(template_name_list): select_template is like get_template, but it takes a list of template names as a parameter. It returns the first template present in the list. If the template does not exist, the TemplateDoesNotExist exception will be triggered.
By default these functions use the TEMPLATE_DIRS setting to load templates. However, internally these functions can specify a template loader to do the heavy lifting.
Some loaders are disabled by default, but you can activate them by editing the TEMPLATE_LOADERS setting. TEMPLATE_LOADERS should be a tuple of strings, where each string represents a template loader. These template loaders are shipped with Django.
django.template.loaders.filesystem.load_template_source: This loader loads templates from the file system based on the TEMPLATE_DIRS setting. It is available by default.
django.template.loaders.app_directories.load_template_source: This loader loads templates from Django applications on the file system. For each application in INSTALLED_APPS, this loader looks in the templates subdirectory. If this directory exists, Django looks for templates there.
This means you can save templates with your application, making it easier to publish Django applications with the default templates. For example, if INSTALLED_APPS contains (‘myproject.polls’,’myproject.music’) , then get_template(‘foo.html’) will look for templates in this order:
Please note that the loader performs an optimization when it is first imported: it caches a list of packages in the templates subdirectory of INSTALLED_APPS.
This loader is enabled by default.
django.template.loaders.eggs.load_template_source: This loader is similar to app_directories, except that it loads templates from Python eggs instead of the file system. This loader is disabled by default; if you use eggs to publish your app, you need to enable it. Python eggs can compress Python code into a single file.
Django uses template loaders in the order specified in the TEMPLATE_LOADERS setting. It uses each loader one by one until it finds a matching template.