在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 教程/ Python/ API
提示和技巧
從其它的模板引擎切換
集成
沙箱
擴展
常見問題
介紹
模板設計者文檔
API

API

本文檔描述 Jinja2 的 API 而不是模板語言。這對實現(xiàn)模板接口,而非創(chuàng)建 Jinja2 模板,是最有用的參考,

基礎

Jinja2 使用一個名為 Environment 的中心對象。這個類的實例用于存儲配 置、全局對象,并用于從文件系統(tǒng)或其它位置加載模板。即使你通過:class:Template 類的構造函數(shù)用字符串創(chuàng)建模板,也會為你自動創(chuàng)建一個環(huán)境,盡管是共享的。

大多數(shù)應用在應用初始化時創(chuàng)建一個 Environment 對象,并用它加載模板。 在某些情況下,如果使用多份配置,使用并列的多個環(huán)境無論如何是有用的。

配置 Jinja2 為你的應用加載文檔的最簡單方式看起來大概是這樣:

    from jinja2 import Environment, PackageLoader
    env = Environment(loader=PackageLoader('yourapplication', 'templates'))

這會創(chuàng)建一個默認設定下的模板環(huán)境和一個在 yourapplication python 包中的 templates 文件夾中尋找模板的加載器。多個加載器是可用的,如果你需要從 數(shù)據(jù)庫或其它資源加載模板,你也可以自己寫一個。

你只需要調(diào)用 get_template() 方法從這個環(huán)境中加載模板,并會返回已加載的 Template:

    template = env.get_template('mytemplate.html')

用若干變量來渲染它,調(diào)用 render() 方法:

    print template.render(the='variables', go='here')

使用一個模板加載器,而不是向 TemplateEnvironment.from_string() 傳遞字符串,有許多好處。除了使用上便利, 也使得模板繼承成為可能。

Unicode

Jinja2 內(nèi)部使用 Unicode ,這意味著你需要向渲染函數(shù)傳遞 Unicode 對象或只包含 ASCII 字符的字符串。此外,換行符按照默認 UNIX 風格規(guī)定行序列結束( n )。

Python 2.x 支持兩種表示字符串對象的方法。一種是 str 類型,另一種是 unicode 類型,它們都繼承于 basestring 類型。不幸的是,默認的 str 不 應該用于存儲基于文本的信息,除非只用到 ASCII 字符。在 Python 2.6 中,可以 在模塊層指定 unicode 為默認值,而在 Python 3 中會是默認值。

要顯式使用一個 Unicode 字符串,你需要給字符串字面量加上 u 前綴: u'H?nsel und Gretel sagen Hallo' 。這樣 Python 會用當前模塊的字符編碼來 解碼字符串,來把字符串存儲為 Unicode 。如果沒有指定編碼,默認是 ASCII , 這意味著你不能使用任何非 ASCII 的標識符。

在使用 Unicode 字面量的 Python 模塊的首行或第二行添加下面的注釋,來妥善設 置模塊編碼:

我們推薦為 Python 模塊和模板使用 utf-8 編碼,因為在 utf-8 中,可以表示 Unicode 中的每個字符,并且向后兼容 ASCII 。對于 Jinja2 ,模板的默認編碼 假定為 utf-8 。

用 Jinja2 來處理非 Unicode 數(shù)據(jù)是不可能的。這是因為 Jinja2 已經(jīng)在語言層 使用了 Unicode 。例如 Jinja2 在表達式中把不間斷空格視為有效的空格,這需要 獲悉編碼或操作一個 Unicode 字符串。

關于 Python 中 Unicode 的更多細節(jié),請閱讀完善的 Unicode documentation 。

另一件重要的事情是 Jinja2 如何處理模板中的字符串字面量。原生實現(xiàn)會對所有 字符串字面量使用 Unicode ,但在過去這是有問題的,因為一些庫顯式地檢查它 們的類型是否為 str 。例如 datetime.strftime 不接受 Unicode 參數(shù)。 為了不徹底破壞它, Jinja2 對只有 ASCII 的字符串返回 str,而對其它返回 unicode:

    >>> m = Template(u"{% set a, b = 'foo', 'f??' %}").module
    >>> m.a
    'foo'
    >>> m.b
    u'fxf6xf6'

高層 API

高層 API 即是你會在應用中用于加載并渲染模板的 API 。 低層 API 相反,只在你想深入挖掘 Jinja2 或 開發(fā)擴展 時有用。

class jinja2.``Environment([options])

The core component of Jinja is the Environment. It contains important shared variables like configuration, filters, tests, globals and others. Instances of this class may be modified if they are not shared and if no template was loaded so far. Modifications on environments after the first template was loaded will lead to surprising effects and undefined behavior.

Here the possible initialization parameters:

block_start_string
The string marking the begin of a block. Defaults to '{%'.
block_end_string
The string marking the end of a block. Defaults to '%}'.
variable_start_string
The string marking the begin of a print statement. Defaults to '{{'.
variable_end_string
The string marking the end of a print statement. Defaults to '}}'.
comment_start_string
The string marking the begin of a comment. Defaults to '{#'.
comment_end_string
The string marking the end of a comment. Defaults to '#}'.
line_statement_prefix
If given and a string, this will be used as prefix for line based statements. See also [行語句][3].
line_comment_prefix

If given and a string, this will be used as prefix for line based based comments. See also [行語句][3].

trim_blocks
If this is set to True the first newline after a block is removed (block, not variable tag!). Defaults to False.
lstrip_blocks
If this is set to True leading spaces and tabs are stripped from the start of a line to a block. Defaults to False.
newline_sequence
The sequence that starts a newline. Must be one of 'r', 'n' or 'rn'. The default is 'n' which is a useful default for Linux and OS X systems as well as web applications.
keep_trailing_newline

Preserve the trailing newline when rendering templates. The default is False, which causes a single newline, if present, to be stripped from the end of the template.

extensions
List of Jinja extensions to use. This can either be import paths as strings or extension classes. For more information have a look at [the extensions documentation][2].
optimized
should the optimizer be enabled? Default is True.
undefined
Undefined or a subclass of it that is used to represent undefined values in the template.
finalize
A callable that can be used to process the result of a variable expression before it is output. For example one can convert None implicitly into an empty string here.
autoescape

If set to true the XML/HTML autoescaping feature is enabled by default. For more details about auto escaping see Markup. As of Jinja 2.4 this can also be a callable that is passed the template name and has to return True or False depending on autoescape should be enabled by default.

Changed in version 2.4: autoescape can now be a function

loader
The template loader for this environment.
cache_size
The size of the cache. Per default this is 50 which means that if more than 50 templates are loaded the loader will clean out the least recently used template. If the cache size is set to 0 templates are recompiled all the time, if the cache size is -1 the cache will not be cleaned.
auto_reload
Some loaders load templates from locations where the template sources may change (ie: file system or database). If auto_reload is set to True (default) every time a template is requested the loader checks if the source changed and if yes, it will reload the template. For higher performance it's possible to disable that.
bytecode_cache

If set to a bytecode cache object, this object will provide a cache for the internal Jinja bytecode so that templates don't have to be parsed if they were not changed.

See 字節(jié)碼緩存 for more information.

shared

如果模板通過 Template 構造函數(shù)創(chuàng)建,會自動創(chuàng)建一個環(huán)境。這 些環(huán)境被創(chuàng)建為共享的環(huán)境,這意味著多個模板擁有相同的匿名環(huán)境。對所有 模板共享環(huán)境,這個屬性為 True ,反之為 False 。

sandboxed

如果環(huán)境在沙箱中,這個屬性為 True 。沙箱模式見文檔中的 [SandboxedEnvironment][4] 。

filters

該環(huán)境的過濾器字典。只要沒有加載過模板,添加新過濾器或刪除舊的都是 安全的。自定義過濾器見 自定義過濾器 。有效的過濾器名稱見 標識符的說明

tests

該環(huán)境的測試函數(shù)字典。只要沒有加載過模板,修改這個字典都是安全的。 自定義測試見 see 自定義測試 。有效的測試名見 標識符的說明 。

globals

一個全局變量字典。這些變量在模板中總是可用。只要沒有加載過模板,修 改這個字典都是安全的。更多細節(jié)見 全局命名空間 。有效的 對象名見 標識符的說明 。

overlay([options])

Create a new overlay environment that shares all the data with the current environment except of cache and the overridden attributes. Extensions cannot be removed for an overlayed environment. An overlayed environment automatically gets all the extensions of the environment it is linked to plus optional extra extensions.

Creating overlays should happen after the initial environment was set up completely. Not all attributes are truly linked, some are just copied over so modifications on the original environment may not shine through.

undefined([hint, obj, name, exc])

為 name 創(chuàng)建一個新 Undefined 對象。這對可能為某些操作返回 未定義對象過濾器和函數(shù)有用。除了 hint ,為了良好的可讀性,所有參數(shù) 應該作為關鍵字參數(shù)傳入。如果提供了 hint ,它被用作異常的錯誤消息, 否則錯誤信息會由 obj 和 name 自動生成。 exc 為生成未定義對象而 不允許未定義的對象時拋出的異常。默認的異常是 UndefinedError 。 如果提供了 hint , name 會被發(fā)送。

創(chuàng)建一個未定義對象的最常用方法是只提供名稱:

return environment.undefined(name='some_name')

這意味著名稱 some_name 未被定義。如果名稱來自一個對象的屬性,把 持有它的對象告知未定義對象對豐富錯誤消息很有意義:

if not hasattr(obj, 'attr'):
    return environment.undefined(obj=obj, name='attr')

更復雜的例子中,你可以提供一個 hint 。例如 [first()][5] 過濾器 用這種方法創(chuàng)建一個未定義對象:

return environment.undefined('no first item, sequence was empty')

如果 name 或 obj 是已知的(比如訪問了了一個屬性),它應該傳遞給 未定義對象,即使提供了自定義的 hint 。這讓未定義對象有可能增強錯誤 消息。

add_extension(extension)

Adds an extension after the environment was created.

compile_expression(source, _undefined_tonone=True)

A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression.

This is useful if applications want to use the same rules as Jinja in template "configuration files" or similar situations.

Example usage:

>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True

Per default the return value is converted to None if the expression returns an undefined value. This can be changed by setting undefined_to_none to False.

>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined
compile_templates(target, extensions=None, _filterfunc=None, zip='deflated', _logfunction=None, _ignoreerrors=True, _pycompile=False)

Finds all the templates the loader can find, compiles them and stores them in target. If zip is None, instead of in a zipfile, the templates will be will be stored in a directory. By default a deflate zip algorithm is used, to switch to the stored algorithm, zip can be set to 'stored'.

extensions and filter_func are passed to list_templates(). Each template returned will be compiled to the target folder or zipfile.

By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set ignore_errors to False and you will get an exception on syntax errors.

If py_compile is set to True .pyc files will be written to the target instead of standard .py files. This flag does not do anything on pypy and Python 3 where pyc files are not picked up by itself and don't give much benefit.

extend(**attributes)

Add the items to the instance of the environment if they do not exist yet. This is used by [extensions][6] to register callbacks and configuration values without breaking inheritance.

from_string(source, globals=None, _templateclass=None)

Load a template from a string. This parses the source given and returns a Template object.

get_or_select_template(_template_name_orlist, parent=None, globals=None)

Does a typecheck and dispatches to select_template() if an iterable of template names is given, otherwise to get_template().

get_template(name, parent=None, globals=None)

Load a template from the loader. If a loader is configured this method ask the loader for the template and returns a Template. If the parent parameter is not None, join_path() is called to get the real template name before loading.

The globals parameter can be used to provide template wide globals. These variables are available in the context at render time.

If the template does not exist a TemplateNotFound exception is raised.

Changed in version 2.4: If name is a Template object it is returned from the function unchanged.

join_path(template, parent)

Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the template parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name.

Subclasses may override this method and implement template path joining here.

list_templates(extensions=None, _filterfunc=None)

Returns a list of templates for this environment. This requires that the loader supports the loader's list_templates() method.

If there are other files in the template folder besides the actual templates, the returned list can be filtered. There are two ways: either extensions is set to a list of file extensions for templates, or a filter_func can be provided which is a callable that is passed a template name and should return True if it should end up in the result list.

If the loader does not support that, a TypeError is raised.

select_template(names, parent=None, globals=None)

Works like get_template() but tries a number of templates before it fails. If it cannot find any of the templates, it will raise a TemplatesNotFound exception.

Changed in version 2.4: If names contains a Template object it is returned from the function unchanged.

class jinja2.``Template

The central template object. This class represents a compiled template and is used to evaluate it.

Normally the template object is generated from an Environment but it also has a constructor that makes it possible to create a template instance directly using the constructor. It takes the same arguments as the environment constructor but it's not possible to specify a loader.

Every template object has a few methods and members that are guaranteed to exist. However it's important that a template object should be considered immutable. Modifications on the object are not supported.

Template objects created from the constructor rather than an environment do have an environment attribute that points to a temporary environment that is probably shared with other templates created with the constructor and compatible settings.

>>> template = Template('Hello {{ name }}!')
>>> template.render(name='John Doe')
u'Hello John Doe!'

>>> stream = template.stream(name='John Doe')
>>> stream.next()
u'Hello John Doe!'
>>> stream.next()
Traceback (most recent call last):
    ...
StopIteration
globals

該模板的全局變量字典。修改這個字典是不安全的,因為它可能與其它模板或 加載這個模板的環(huán)境共享。

name

模板的加載名。如果模板從字符串加載,這個值為 None 。

filename

模板在文件系統(tǒng)上的文件名,如果沒有從文件系統(tǒng)加載,這個值為 None 。

render([context])

This method accepts the same arguments as the dict constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:

template.render(knights='that say nih')
template.render({'knights': 'that say nih'})

This will return the rendered template as unicode string.

generate([context])

For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as unicode strings.

It accepts the same arguments as render().

stream([context])

Works exactly like generate() but returns a TemplateStream.

make_module(vars=None, shared=False, locals=None)

This method works like the module attribute when called without arguments but it will evaluate the template on every call rather than caching it. It's also possible to provide a dict which is then used as context. The arguments are the same as for the new_context() method.

module

The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer:

>>> t = Template('{% macro foo() %}42{% endmacro %}23')
>>> unicode(t.module)
u'23'
>>> t.module.foo()
u'42'
class jinja2.environment.``TemplateStream

A template stream works pretty much like an ordinary python generator but it can buffer multiple items to reduce the number of total iterations. Per default the output is unbuffered which means that for every unbuffered instruction in the template one unicode string is yielded.

If buffering is enabled with a buffer size of 5, five items are combined into a new unicode string. This is mainly useful if you are streaming big templates to a client via WSGI which flushes after each iteration.

disable_buffering()

Disable the output buffering.

dump(fp, encoding=None, errors='strict')

Dump the complete stream into a file or file-like object. Per default unicode strings are written, if you want to encode before writing specify an encoding.

Example usage:

Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
enable_buffering(size=5)

Enable buffering. Buffer size items before yielding them.

自動轉(zhuǎn)義

從 Jinja 2.4 開始,自動轉(zhuǎn)義的首選途徑就是啟用 [自動轉(zhuǎn)義擴展][7] 并為自動轉(zhuǎn)義配置一個合適的默認值。這使得在單個模板基礎上開關自動轉(zhuǎn)義成為 可能(比如 HTML 對 文本)

這里推薦為以 .html 、 .htm 、 .xml 以及 .xhtml 的模板開啟 自動轉(zhuǎn)義 ,并對所有其它擴展名禁用:

    def guess_autoescape(template_name):
        if template_name is None or '.' not in template_name:
            return False
        ext = template_name.rsplit('.', 1)[1]
        return ext in ('html', 'htm', 'xml')

    env = Environment(autoescape=guess_autoescape,
                      loader=PackageLoader('mypackage'),
                      extensions=['jinja2.ext.autoescape'])

假設實現(xiàn)一個自動轉(zhuǎn)義函數(shù),確保你也視 None 為有效模板名接受。這會在從字符 串生成模板時傳遞。

可以用 autoescape 塊在模板內(nèi)臨時地更改這種行為。(見 [自動轉(zhuǎn)義擴展][8] )。

標識符的說明

Jinja2 使用正規(guī)的 Python 2.x 命名規(guī)則。有效的標識符必須匹配 [a-zA-Z_][a-zA-Z0-9_]* 。事實上,當前不允許非 ASCII 字符。這個限制可能 會在 Python 3 充分規(guī)定 unicode 標識符后消失。

過濾器和測試會在獨立的命名空間中查找,與標識符語法有細微區(qū)別。過濾器和測 試可以包含點,用于按主題給過濾器和測試分組。例如,把一個名為 to.unicode 的函數(shù)添加到過濾器字典是完全有效的。過濾器和測試標識符的正則表達式是 [a-zA-Z_][a-zA-Z0-9_]*(.[a-zA-Z_][a-zA-Z0-9_]*)* 。

未定義類型

這些類可以用作未定義類型。 Environment 的構造函數(shù)接受一個可以是 那些類或一個 Undefined 的自定義子類的 undefined 參數(shù)。無論何時, 這些對象創(chuàng)建或返回時,模板引擎都不能查出其名稱或訪問其屬性。未定義值上的 某些操作之后是允許的,而其它的會失敗。

最接近常規(guī) Python 行為的是 StrictUndefined ,如果它是一個未定義對象, 它不允許除了測試之外的一切操作。

class jinja2.``Undefined

The default undefined type. This undefined type can be printed and iterated over, but every other access will raise an UndefinedError:

    >>> foo = Undefined(name='foo')
    >>> str(foo)
    ''
    >>> not foo
    True
    >>> foo + 42
    Traceback (most recent call last):
      ...
    UndefinedError: 'foo' is undefined
_undefined_hint

None 或給未定義對象的錯誤消息 unicode 字符串。

_undefined_obj

None 或引起未定義對象創(chuàng)建的對象(例如一個屬性不存在)。

_undefined_name

未定義變量/屬性的名稱,如果沒有此類信息,留為 None 。

_undefined_exception

未定義對象想要拋出的異常。這通常是 UndefinedErrorSecurityError 之一。

_fail_with_undefined_error(*args, **kwargs)

參數(shù)任意,調(diào)用這個方法時會拋出帶有由未定義對象上存儲的未定義 hint 生成的錯誤信息的 _undefined_exception 異常。

class jinja2.``DebugUndefined

An undefined that returns the debug info when printed.

    >>> foo = DebugUndefined(name='foo')
    >>> str(foo)
    '{{ foo }}'
    >>> not foo
    True
    >>> foo + 42
    Traceback (most recent call last):
      ...
    UndefinedError: 'foo' is undefined
class jinja2.``StrictUndefined

An undefined that barks on print and iteration as well as boolean tests and all kinds of comparisons. In other words: you can do nothing with it except checking if it's defined using the defined test.

    >>> foo = StrictUndefined(name='foo')
    >>> str(foo)
    Traceback (most recent call last):
      ...
    UndefinedError: 'foo' is undefined
    >>> not foo
    Traceback (most recent call last):
      ...
    UndefinedError: 'foo' is undefined
    >>> foo + 42
    Traceback (most recent call last):
      ...
    UndefinedError: 'foo' is undefined

未定義對象由調(diào)用 [undefined][9] 創(chuàng)建。

實現(xiàn)

Undefined 對象通過重載特殊的 underscore 方法實現(xiàn)。例如 默認的 Undefined 類實現(xiàn) unicode 為返回一個空字符串,但 int 和其它會始終拋出異常。你可以自己通過返回 0 實現(xiàn)轉(zhuǎn)換為 int:

    class NullUndefined(Undefined):
        def __int__(self):
            return 0
        def __float__(self):
            return 0.0

要禁用一個方法,重載它并拋出 _undefined_exception 。因 為這在未定義對象中非常常用,未定義對象有輔助方法 _fail_with_undefined_error() 自動拋出錯誤。這里的一個類 工作類似正規(guī)的 Undefined ,但它在迭代時阻塞:

class NonIterableUndefined(Undefined):
iter = Undefined._fail_with_undefined_error

上下文

class jinja2.runtime.``Context

The template context holds the variables of a template. It stores the values passed to the template and also the names the template exports. Creating instances is neither supported nor useful as it's created automatically at various stages of the template evaluation and should not be created by hand.

The context is immutable. Modifications on parent must not happen and modifications on vars are allowed from generated template code only. Template filters and global functions marked as contextfunction()s get the active context passed as first argument and are allowed to access the context read-only.

The template context supports read only dict operations (get, keys, values, items, iterkeys, itervalues, iteritems, getitem, contains). Additionally there is a resolve() method that doesn't fail with a KeyError but returns an Undefined object for missing variables.

parent

一個模板查找的只讀全局變量的詞典。這些變量可能來自另一個 Context ,或是 Environment.globals ,或是 Template.globals ,或指向一個由全局變量和傳遞到渲染函數(shù)的變 量聯(lián)立的字典。它一定不能被修改。

vars

模板局域變量。這個列表包含環(huán)境和來自 parent 范圍的上下文函數(shù) 以及局域修改和從模板中導出的變量。模板會在模板求值時修改這個字典, 但過濾器和上下文函數(shù)不允許修改它。

environment

加載該模板的環(huán)境

exported_vars

這設定了所有模板導出量的名稱。名稱對應的值在 vars 字典中。 可以用 get_exported() 獲取一份導出變量的拷貝字典。

name

擁有此上下文的模板的載入名。

blocks

模板中塊當前映射的字典。字典中的鍵是塊名稱,值是注冊的塊的列表。每個 列表的最后一項是當前活動的塊(繼承鏈中最新的)。

eval_ctx

當前的 求值上下文 。

call(callable, *args, **kwargs)

Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a contextfunction() or environmentfunction().

get_all()

Return a copy of the complete context as dict including the exported variables.

get_exported()

Get a new dict with the exported variables.

resolve(key)

Looks up a variable like getitem or get but returns an Undefined object with the name of the name looked up.

實現(xiàn)

Python frame 中的局域變量在函數(shù)中是不可變的,出于同樣的原因,上下文是不可 變的。 Jinja2 和 Python 都不把上下文/ frame 作為變量的數(shù)據(jù)存儲,而只作為 主要的數(shù)據(jù)源。

當模板訪問一個模板中沒有定義的變量時, Jinja2 在上下文中查找變量,此后, 這個變量被視為其是在模板中定義得一樣。

加載器

加載器負責從諸如文件系統(tǒng)的資源加載模板。環(huán)境會把編譯的模塊像 Python 的 sys.modules 一樣保持在內(nèi)存中。與 sys.models 不同,無論如何這個 緩存默認有大小限制,且模板會自動重新加載。 所有的加載器都是 BaseLoader 的子類。如果你想要創(chuàng)建自己的加載器,繼 承 BaseLoader 并重載 get_source 。

class jinja2.``BaseLoader

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 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)

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)

Loads a template. This method looks up the template in the cache or loads one by calling get_source(). Subclasses should not override this method as loaders working on collections of other loaders (such as PrefixLoader or ChoiceLoader) will not call this method but get_source directly.

這里有一個 Jinja2 提供的內(nèi)置加載器的列表:

class jinja2.``FileSystemLoader(searchpath, encoding='utf-8')

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 the encoding parameter to something else.

class jinja2.``PackageLoader(_packagename, _packagepath='templates', encoding='utf-8')

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 the encoding 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)

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(_loadfunc)

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 return True if the template is still up to date. For more details have a look at BaseLoader.get_source() which has the same return value.

class jinja2.``PrefixLoader(mapping, delimiter='/')

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 fil

上一篇:介紹下一篇:提示和技巧