上下文

2018-02-24 15:39 更新

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, getitemcontains). Additionally there is aresolve() method that doesn’t fail with a KeyError but returns an Undefined object for missing variables.

parent

一个模板查找的只读全局变量的词典。这些变量可能来自另一个 Context ,或是Environment.globals ,或是 Template.globals ,或指向一个由全局变量和传递到渲染函数的变 量联立的字典。它一定不能被修改。

vars

模板局域变量。这个列表包含环境和来自 parent 范围的上下文函数 以及局域修改和从模板中导出的变量。模板会在模板求值时修改这个字典, 但过滤器和上下文函数不允许修改它。

environment

加载该模板的环境

exported_vars

这设定了所有模板导出量的名称。名称对应的值在 vars 字典中。 可以用get_exported() 获取一份导出变量的拷贝字典。

name

拥有此上下文的模板的载入名。

blocks

模板中块当前映射的字典。字典中的键是块名称,值是注册的块的列表。每个 列表的最后一项是当前活动的块(继承链中最新的)。

eval_ctx

当前的 求值上下文 。

call(callableargskwargs*)

Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is acontextfunction() 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.

实现

Python frame 中的局域变量在函数中是不可变的,出于同样的原因,上下文是不可 变的。 Jinja2 和 Python 都不把上下文/ frame 作为变量的数据存储,而只作为 主要的数据源。

当模板访问一个模板中没有定义的变量时, Jinja2 在上下文中查找变量,此后, 这个变量被视为其是在模板中定义得一样。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号