加載器負責從諸如文件系統的資源加載模板。環境會把編譯的模塊像 Python 的sys.modules?一樣保持在內存中。與?sys.models?不同,無論如何這個 緩存默認有大小限制,且模板會自動重新加載。 所有的加載器都是?[BaseLoader](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.BaseLoader "jinja2.BaseLoader")?的子類。如果你想要創建自己的加載器,繼 承?[BaseLoader](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.BaseLoader "jinja2.BaseLoader")?并重載?get_source?。
*class?*jinja2.BaseLoader[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.BaseLoader "Permalink to this definition")
Baseclass for all loaders. Subclass this and override?get_source?to implement a custom loading mechanism. The environment provides a?get_template?method that calls the loader’s?load?method to get the?[Template](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Template "jinja2.Template")?object.
A very basic example for a loader that looks up templates on the file system 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)
~~~
get_source(*environment*,?*template*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.BaseLoader.get_source "Permalink to this definition")
Get the template source, filename and reload helper for a template. It’s passed the environment and template name and has to return a tuple in the form(source,?filename,?uptodate)?or raise a?TemplateNotFound?error if it can’t locate the template.
The source part of the returned tuple must be the source of the template as unicode string or a ASCII bytestring. The filename should be the name of the file on the filesystem if it was loaded from there, otherwise?None. The filename is used by python for the tracebacks if no loader extension is used.
The last item in the tuple is the?uptodate?function. If auto reloading is enabled it’s always called to check if the template changed. No arguments are passed so the function must store the old state somewhere (for example in a closure). If it returns?False?the template will be reloaded.
load(*environment*,?*name*,?*globals=None*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.BaseLoader.load "Permalink to this definition")
Loads a template. This method looks up the template in the cache or loads one by calling?[get_source()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.BaseLoader.get_source "jinja2.BaseLoader.get_source"). Subclasses should not override this method as loaders working on collections of other loaders (such as?[PrefixLoader](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.PrefixLoader "jinja2.PrefixLoader")?or?[ChoiceLoader](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.ChoiceLoader "jinja2.ChoiceLoader")) will not call this method but?get_source?directly.
這里有一個 Jinja2 提供的內置加載器的列表:
*class?*jinja2.FileSystemLoader(*searchpath*,?*encoding='utf-8'*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.FileSystemLoader "Permalink to this definition")
Loads templates from the file system. This loader can find templates in 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 multiple locations are wanted a list of them which is then looked up in the given order:
~~~
>>> loader = FileSystemLoader('/path/to/templates')
>>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])
~~~
Per default the template encoding is?'utf-8'?which can be changed by setting theencoding?parameter to something else.
*class?*jinja2.PackageLoader(*package_name*,?*package_path='templates'*,?*encoding='utf-8'*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.PackageLoader "Permalink to this definition")
Load templates from python eggs or packages. It is constructed with the name of the python package and the path to the templates in that package:
~~~
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 changed by setting theencoding?parameter to something else. Due to the nature of eggs it’s only possible to reload templates if the package was loaded from the file system and not a zip file.
*class?*jinja2.DictLoader(*mapping*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.DictLoader "Permalink to this definition")
Loads a template from a python dict. It’s passed a dict of unicode strings 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*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.FunctionLoader "Permalink to this definition")
A loader that is passed a function which does the loading. The function becomes the name of the template passed and has to return either an 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 enabled and has to returnTrue?if the template is still up to date. For more details have a look at[BaseLoader.get_source()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.BaseLoader.get_source "jinja2.BaseLoader.get_source")?which has the same return value.
*class?*jinja2.PrefixLoader(*mapping*,?*delimiter='/'*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.PrefixLoader "Permalink to this definition")
A loader that is passed a dict of loaders where each loader is bound to a prefix. The prefix is delimited from the template by a slash per default, which can be changed by setting the?delimiter?argument to something 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*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.ChoiceLoader "Permalink to this definition")
This loader works like the?PrefixLoader?just that no prefix is specified. If a template could not be found by one loader the next one is 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 templates from a different location.
*class?*jinja2.ModuleLoader(*path*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.ModuleLoader "Permalink to this definition")
This loader loads templates from precompiled templates.
Example usage:
~~~
>>> loader = ChoiceLoader([
... ModuleLoader('/path/to/compiled/templates'),
... FileSystemLoader('/path/to/templates')
... ])
~~~
Templates can be precompiled with?[Environment.compile_templates()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.Environment.compile_templates "jinja2.Environment.compile_templates").
- 介紹
- 預備知識
- 安裝
- 基本 API 使用
- 實驗性的 Python 3 支持
- API
- 基礎
- Unicode
- 高層 API
- 自動轉義
- 標識符的說明
- 未定義類型
- 上下文
- 加載器
- 字節碼緩存
- 實用工具
- 異常
- 自定義過濾器
- 求值上下文
- 自定義測試
- 全局命名空間
- 低層 API
- 元 API
- 沙箱
- API
- 運算符攔截
- 模板設計者文檔
- 概要
- 變量
- 過濾器
- 測試
- 注釋
- 空白控制
- 轉義
- 行語句
- 模板繼承
- HTML 轉義
- 控制結構清單
- 導入上下文行為
- 表達式
- 內置過濾器清單
- 內置測試清單
- 全局函數清單
- 擴展
- 自動轉義擴展
- 擴展
- 添加擴展
- i18n 擴展
- 表達式語句
- 循環控制
- With 語句
- 自動轉義擴展
- 編寫擴展
- 集成
- Babel 集成
- Pylons
- TextMate
- Vim
- 從其它的模板引擎切換
- Jinja1
- Django
- Mako
- 提示和技巧
- Null-Master 退回
- 交替的行
- 高亮活動菜單項
- 訪問父級循環