加载器

加载器负责从诸如文件系统的资源加载模板。环境会把编译的模块像Python 的 sys.modules 一样保持在内存中。与 sys.models 不同,无论如何这个缓存默认有大小限制,且模板会自动重新加载。所有的加载器都是 BaseLoader 的子类。如果你想要创建自己的加载器,继承 BaseLoader 并重载 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.

这里有一个 Jinja2 提供的内置加载器的列表:

  • class _jinja2.FileSystemLoader(_searchpath, encoding='utf-8')
  • 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.

  • 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 becomes the name of the template passed 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().