低層 API

2018-02-24 15:39 更新

低層 API 暴露的功能對理解一些實(shí)現(xiàn)細(xì)節(jié)、調(diào)試目的或高級?擴(kuò)展?技巧是有用的。除非你準(zhǔn)確地了解你在做什么,否則 不推薦使用這些 API 。

Environment.lex(source,?name=None,?filename=None)

Lex the given sourcecode and return a generator that yields tokens as tuples in the form?(lineno,?token_type,?value). This can be useful for?extension development?and debugging templates.

This does not perform preprocessing. If you want the preprocessing of the extensions to be applied you have to filter source through the?preprocess()?method.

Environment.parse(source,?name=None,?filename=None)

Parse the sourcecode and return the abstract syntax tree. This tree of nodes is used by the compiler to convert the template into executable source- or bytecode. This is useful for debugging or to extract information from templates.

If you are?developing Jinja2 extensions?this gives you a good overview of the node tree generated.

Environment.preprocess(source,?name=None,?filename=None)

Preprocesses the source with all extensions. This is automatically called for all parsing and compiling methods but?not?for?lex()?because there you usually only want the actual source tokenized.

Template.new_context(vars=None,?shared=False,?locals=None)

Create a new?Context?for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to?True?the data is passed as it to the context without adding the globals.

locals?can be a dict of local variables for internal usage.

Template.root_render_func(context)

這是低層的渲染函數(shù)。它接受一個(gè)必須由相同模板或兼容的模板的?new_context()?創(chuàng)建的?Context?。這個(gè)渲染函數(shù)由編譯器從 模板代碼產(chǎn)生,并返回一個(gè)生產(chǎn) unicode 字符串的生成器。

如果模板代碼中發(fā)生了異常,模板引擎不會重寫異常而是直接傳遞原始的異常。 事實(shí)上,這個(gè)函數(shù)只在?render()?/?generate()?/?stream()?的調(diào)用里被調(diào)用。

Template.blocks

一個(gè)塊渲染函數(shù)的字典。其中的每個(gè)函數(shù)與?root_render_func()?的工作 相同,并且有相同的限制。

Template.is_up_to_date

如果有可用的新版本模板,這個(gè)屬性是?False?,否則是?True?。

注意

低層 API 是易碎的。未來的 Jinja2 的版本將不會試圖以不向后兼容的方式修改它, 而是在 Jinja2 核心的修改中表現(xiàn)出來。比如如果 Jinja2 在之后的版本中引入一 個(gè)新的 AST 節(jié)點(diǎn),它會由?parse()?返回。

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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號