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

API

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

基礎(chǔ)

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

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

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

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

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

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

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

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

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

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

Unicode

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

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

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

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

我們推薦為 Python 模塊和模板使用 utf-8 編碼,因?yàn)樵?utf-8 中,可以表示 Unicode 中的每個(gè)字符,并且向后兼容 ASCII 。對(duì)于 Jinja2 ,模板的默認(rèn)編碼 假定為 utf-8 。

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

關(guān)于 Python 中 Unicode 的更多細(xì)節(jié),請(qǐng)閱讀完善的 Unicode documentation

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

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

高層 API

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

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 構(gòu)造函數(shù)創(chuàng)建,會(huì)自動(dòng)創(chuàng)建一個(gè)環(huán)境。這 些環(huán)境被創(chuàng)建為共享的環(huán)境,這意味著多個(gè)模板擁有相同的匿名環(huán)境。對(duì)所有 模板共享環(huán)境,這個(gè)屬性為 True ,反之為 False 。

sandboxed

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

filters

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

tests

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

globals

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

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)建一個(gè)新 Undefined 對(duì)象。這對(duì)可能為某些操作返回 未定義對(duì)象過濾器和函數(shù)有用。除了 hint ,為了良好的可讀性,所有參數(shù) 應(yīng)該作為關(guān)鍵字參數(shù)傳入。如果提供了 hint ,它被用作異常的錯(cuò)誤消息, 否則錯(cuò)誤信息會(huì)由 obj 和 name 自動(dòng)生成。 exc 為生成未定義對(duì)象而 不允許未定義的對(duì)象時(shí)拋出的異常。默認(rèn)的異常是 UndefinedError 。 如果提供了 hint , name 會(huì)被發(fā)送。

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

return environment.undefined(name='some_name')

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

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

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

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

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

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

該模板的全局變量字典。修改這個(gè)字典是不安全的,因?yàn)樗赡芘c其它模板或 加載這個(gè)模板的環(huán)境共享。

name

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

filename

模板在文件系統(tǒng)上的文件名,如果沒有從文件系統(tǒng)加載,這個(gè)值為 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.

自動(dòng)轉(zhuǎn)義

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

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

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

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

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

標(biāo)識(shí)符的說明

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

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

未定義類型

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

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

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 或給未定義對(duì)象的錯(cuò)誤消息 unicode 字符串。

_undefined_obj

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

_undefined_name

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

_undefined_exception

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

_fail_with_undefined_error(*args, **kwargs)

參數(shù)任意,調(diào)用這個(gè)方法時(shí)會(huì)拋出帶有由未定義對(duì)象上存儲(chǔ)的未定義 hint 生成的錯(cuò)誤信息的 _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

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

實(shí)現(xiàn)

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

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

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

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

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

vars

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

environment

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

exported_vars

這設(shè)定了所有模板導(dǎo)出量的名稱。名稱對(duì)應(yīng)的值在 vars 字典中。 可以用 get_exported() 獲取一份導(dǎo)出變量的拷貝字典。

name

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

blocks

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

eval_ctx

當(dāng)前的 求值上下文 。

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.

實(shí)現(xiàn)

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

當(dāng)模板訪問一個(gè)模板中沒有定義的變量時(shí), Jinja2 在上下文中查找變量,此后, 這個(gè)變量被視為其是在模板中定義得一樣。

加載器

加載器負(fù)責(zé)從諸如文件系統(tǒng)的資源加載模板。環(huán)境會(huì)把編譯的模塊像 Python 的 sys.modules 一樣保持在內(nèi)存中。與 sys.models 不同,無論如何這個(gè) 緩存默認(rèn)有大小限制,且模板會(huì)自動(dòng)重新加載。 所有的加載器都是 BaseLoader 的子類。如果你想要?jiǎng)?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.

這里有一個(gè) 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

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