In general, you will store the template as a file in the file system, but you can also use the custom template loaders to load the templates from other sources.
Django has two ways to load a template
- Django.template.loader.get_template (template_name): Get_template Returns a compiled template, based on the given template name (a Templates object). If the template does not exist, the templatedoesnotexist exception is triggered.
- Django.template.loader.select_template (template_name_list): Select_template is much like get_template, but it is a list of template names as parameters. It returns the first template that exists 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 the template. However, inside these functions you can specify a template loader to accomplish these heavy tasks.
Some loaders are disabled by default, but you can activate them by editing the template_loaders settings. Template_loaders should be a tuple of strings, where each string represents a template loader. These template loaders are published with Django.
Django.template.loaders.filesystem.load_template_source: This loader loads the template from the file system based on the Template_dirs settings. It is available by default.
Django.template.loaders.app_directories.load_template_source: This loader loads the template from a Django application on the file system. For each application in Installed_apps, the loader looks for the templates subdirectory. If this directory exists, Django is there looking for templates.
This means you can save the template with your app, making it easier for Django apps to publish with the default template. For example, if Installed_apps contains (' Myproject.polls ', ' myproject.music '), then Get_template (' foo.html ') will find the template in this order:
/path/to/myproject/polls/templates/foo.html /path/to/myproject/music/templates/foo.html
Note that the loader performs an optimization when it is first imported: It caches a list that contains packages with templates subdirectories in 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, and if you use eggs to publish your app, you need to enable it. Python eggs can compress python code into a file.
Django uses the template loader in the order of the Template_loaders settings. It uses each loader individually until a matching template is found.