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 the
Template
object.
A very basic example for a loader that looks up templates on the filesystem could look like this:
from jinja2 import BaseLoader, TemplateNotFound
from os.path import join, exists, getmtime
class MyLoader(BaseLoader):
def __init__(self, path):
self.path = path
def get_source(self, environment, template):
path = join(self.path, template)
if not exists(path):
raise TemplateNotFound(template)
mtime = getmtime(path)
with file(path) as f:
source = f.read().decode('utf-8')
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 asPrefixLoader
orChoiceLoader
)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:
>>> loader = FileSystemLoader('/path/to/templates')
>>> 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
:
>>> 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:
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:
>>> 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.
>>> def load_template(name):
... if name == 'index.html':
... return '...'
...
>>> 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:
loader = PrefixLoader({
'app1': PackageLoader('mypackage.app1'),
'app2': PackageLoader('mypackage.app2')
})
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.
>>> loader = ChoiceLoader([
... FileSystemLoader('/path/to/user/templates'),
... FileSystemLoader('/path/to/system/templates')
... ])
This is useful if you want to allow users to override builtin templatesfrom a different location.
Example usage:
>>> loader = ChoiceLoader([
... ModuleLoader('/path/to/compiled/templates'),
... FileSystemLoader('/path/to/templates')
... ])
Templates can be precompiled with Environment.compile_templates()
.