低层 API

2018-02-24 15:39 更新

低层 API 暴露的功能对理解一些实现细节、调试目的或高级 扩展 技巧是有用的。除非你准确地了解你在做什么,否则 不推荐使用这些 API 。

Environment.lex(sourcename=Nonefilename=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(sourcename=Nonefilename=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(sourcename=Nonefilename=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=Noneshared=Falselocals=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)

这是低层的渲染函数。它接受一个必须由相同模板或兼容的模板的 new_context() 创建的 Context 。这个渲染函数由编译器从 模板代码产生,并返回一个生产 unicode 字符串的生成器。

如果模板代码中发生了异常,模板引擎不会重写异常而是直接传递原始的异常。 事实上,这个函数只在 render() / generate() / stream() 的调用里被调用。

Template.blocks

一个块渲染函数的字典。其中的每个函数与 root_render_func() 的工作 相同,并且有相同的限制。

Template.is_up_to_date

如果有可用的新版本模板,这个属性是 False ,否则是 True 。

注意

低层 API 是易碎的。未来的 Jinja2 的版本将不会试图以不向后兼容的方式修改它, 而是在 Jinja2 核心的修改中表现出来。比如如果 Jinja2 在之后的版本中引入一 个新的 AST 节点,它会由 parse() 返回。

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

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号