上下文

  • _class _jinja2.runtime.Context
  • The template context holds the variables of a template. It stores thevalues passed to the template and also the names the template exports.Creating instances is neither supported nor useful as it’s createdautomatically at various stages of the template evaluation and should notbe created by hand.

The context is immutable. Modifications on parentmust nothappen and modifications on vars are allowed from generatedtemplate code only. Template filters and global functions marked ascontextfunction()s get the active context passed as first argumentand 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 anUndefined object for missing variables.

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

  • vars

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

  • environment

  • 加载该模板的环境

  • exported_vars

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

  • name

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

  • blocks

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

  • eval_ctx

  • 当前的 求值上下文

  • call(callable, *args, **kwargs)

  • Call the callable with the arguments and keyword argumentsprovided but inject the active context or environment as firstargument if the callable is a contextfunction() orenvironmentfunction().

  • get_all()

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

  • get_exported()

  • Get a new dict with the exported variables.

  • resolve(key)

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

实现

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

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