Loaders

Loaders are responsible for loading templates from a resource such as thefile system. The environment will keep the compiled modules in memory likePython’s sys.modules. Unlike sys.modules however this cache is limited insize by default and templates are automatically reloaded.All loaders are subclasses of BaseLoader. If you want to create yourown loader, subclass BaseLoader and override get_source.

  • class jinja2.BaseLoader
  • Baseclass for all loaders. Subclass this and override get_source toimplement a custom loading mechanism. The environment provides aget_template method that calls the loader’s load method to get theTemplate object.

A very basic example for a loader that looks up templates on the filesystem could look like this:

  1. from jinja2 import BaseLoader, TemplateNotFound
  2. from os.path import join, exists, getmtime
  3. class MyLoader(BaseLoader):
  4. def __init__(self, path):
  5. self.path = path
  6. def get_source(self, environment, template):
  7. path = join(self.path, template)
  8. if not exists(path):
  9. raise TemplateNotFound(template)
  10. mtime = getmtime(path)
  11. with file(path) as f:
  12. source = f.read().decode('utf-8')
  13. return source, path, lambda: mtime == getmtime(path)
  • getsource(_environment, template)
  • Get the template source, filename and reload helper for a template.It’s passed the environment and template name and has to return atuple in the form (source, filename, uptodate) or raise aTemplateNotFound error if it can’t locate the template.

The source part of the returned tuple must be the source of thetemplate as unicode string or a ASCII bytestring. The filename shouldbe the name of the file on the filesystem if it was loaded from there,otherwise None. The filename is used by python for the tracebacksif no loader extension is used.

The last item in the tuple is the uptodate function. If autoreloading is enabled it’s always called to check if the templatechanged. No arguments are passed so the function must store theold state somewhere (for example in a closure). If it returns _False_the template will be reloaded.

  • load(environment, name, globals=None)
  • Loads a template. This method looks up the template in the cacheor loads one by calling get_source(). Subclasses should notoverride this method as loaders working on collections of otherloaders (such as PrefixLoader or ChoiceLoader)will not call this method but get_source directly.

Here a list of the builtin loaders Jinja2 provides:

  • class jinja2.FileSystemLoader(searchpath, encoding='utf-8', followlinks=False)
  • Loads templates from the file system. This loader can find templatesin folders on the file system and is the preferred way to load them.

The loader takes the path to the templates as string, or if multiplelocations are wanted a list of them which is then looked up in thegiven order:

  1. >>> loader = FileSystemLoader('/path/to/templates')
  2. >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])

Per default the template encoding is 'utf-8' which can be changedby setting the encoding parameter to something else.

To follow symbolic links, set the followlinks parameter to True:

  1. >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)

Changelog

Changed in version 2.8+: The followlinks parameter was added.

  • class jinja2.PackageLoader(package_name, package_path='templates', encoding='utf-8')
  • Load templates from python eggs or packages. It is constructed withthe name of the python package and the path to the templates in thatpackage:
  1. loader = PackageLoader('mypackage', 'views')

If the package path is not given, 'templates' is assumed.

Per default the template encoding is 'utf-8' which can be changedby setting the encoding parameter to something else. Due to the natureof eggs it’s only possible to reload templates if the package was loadedfrom the file system and not a zip file.

  • class jinja2.DictLoader(mapping)
  • Loads a template from a python dict. It’s passed a dict of unicodestrings bound to template names. This loader is useful for unittesting:
  1. >>> loader = DictLoader({'index.html': 'source here'})

Because auto reloading is rarely useful this is disabled per default.

  • class jinja2.FunctionLoader(load_func)
  • A loader that is passed a function which does the loading. Thefunction receives the name of the template and has to return eitheran unicode string with the template source, a tuple in the form (source,filename, uptodatefunc) or None if the template does not exist.
  1. >>> def load_template(name):
  2. ... if name == 'index.html':
  3. ... return '...'
  4. ...
  5. >>> loader = FunctionLoader(load_template)

The uptodatefunc is a function that is called if autoreload is enabledand has to return True if the template is still up to date. For moredetails have a look at BaseLoader.get_source() which has the samereturn value.

  • class jinja2.PrefixLoader(mapping, delimiter='/')
  • A loader that is passed a dict of loaders where each loader is boundto a prefix. The prefix is delimited from the template by a slash perdefault, which can be changed by setting the delimiter argument tosomething else:
  1. loader = PrefixLoader({
  2. 'app1': PackageLoader('mypackage.app1'),
  3. 'app2': PackageLoader('mypackage.app2')
  4. })

By loading 'app1/index.html' the file from the app1 package is loaded,by loading 'app2/index.html' the file from the second.

  • class jinja2.ChoiceLoader(loaders)
  • This loader works like the PrefixLoader just that no prefix isspecified. If a template could not be found by one loader the next oneis tried.
  1. >>> loader = ChoiceLoader([
  2. ... FileSystemLoader('/path/to/user/templates'),
  3. ... FileSystemLoader('/path/to/system/templates')
  4. ... ])

This is useful if you want to allow users to override builtin templatesfrom a different location.

  • class jinja2.ModuleLoader(path)
  • This loader loads templates from precompiled templates.

Example usage:

  1. >>> loader = ChoiceLoader([
  2. ... ModuleLoader('/path/to/compiled/templates'),
  3. ... FileSystemLoader('/path/to/templates')
  4. ... ])

Templates can be precompiled with Environment.compile_templates().