template.loaders.base.Loader

class Loader [source]

Loads templates from a given source, such as the filesystem or a database.

get_template_sources(template_name) [source]

A method that takes a template_name and yields Origin instances for each possible source.

For example, the filesystem loader may receive 'index.html' as a template_name argument. This method would yield origins for the full path of index.html as it appears in each template directory the loader looks at.

The method doesn’t need to verify that the template exists at a given path, but it should ensure the path is valid. For instance, the filesystem loader makes sure the path lies under a valid template directory.

get_contents(origin)

Returns the contents for a template given a Origin instance.

This is where a filesystem loader would read contents from the filesystem, or a database loader would read from the database. If a matching template doesn’t exist, this should raise a TemplateDoesNotExist error.

get_template(template_name, skip=None) [source]

Returns a Template object for a given template_name by looping through results from get_template_sources() and calling get_contents(). This returns the first matching template. If no template is found, TemplateDoesNotExist is raised.

The optional skip argument is a list of origins to ignore when extending templates. This allow templates to extend other templates of the same name. It also used to avoid recursion errors.

In general, it is enough to define get_template_sources() and get_contents() for custom template loaders. get_template() will usually not need to be overridden.

load_template_source(template_name, template_dirs=None) [source]

Returns a tuple of (template_string, template_origin), where template_string is a string containing the template contents, and template_origin is a string identifying the template source. A filesystem-based loader may return the full path to the file as the template_origin, for example.

template_dirs is an optional argument used to control which directories the loader will search.

This method is called automatically by load_template() and should be overridden when writing custom template loaders.

Deprecated since version 1.9: Custom loaders should use get_template() and get_contents() instead.

load_template(template_name, template_dirs=None) [source]

Returns a tuple of (template, template_origin), where template is a Template object and template_origin is a string identifying the template source. A filesystem-based loader may return the full path to the file as the template_origin, for example.

Deprecated since version 1.9: Custom loaders should use get_template() and get_contents() instead.

Building your own

For examples, read the source code for Django’s built-in loaders.

doc_Django
2016-10-09 18:39:49
Comments
Leave a Comment

Please login to continue.