上下文

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,?getitem,?contains). 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?,或指向一個由全局變量和傳遞到渲染函數(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 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.

實現(xiàn)

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

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

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號