低层 API
低层 API 暴露的功能对理解一些实现细节、调试目的或高级扩展 技巧是有用的。除非你准确地了解你在做什么,否则不推荐使用这些 API 。
- Environment.lex(source, name=None, filename=None)
- Lex the given sourcecode and return a generator that yieldstokens as tuples in the form (lineno,tokentype,value).This can be useful for [_extension development]($006032b572352ceb.md#writing-extensions)and debugging templates.
This does not perform preprocessing. If you want the preprocessingof the extensions to be applied you have to filter source throughthe preprocess() method.
- Environment.parse(source, name=None, filename=None)
- Parse the sourcecode and return the abstract syntax tree. Thistree of nodes is used by the compiler to convert the template intoexecutable source- or bytecode. This is useful for debugging or toextract information from templates.
If you are developing Jinja2 extensionsthis 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 automaticallycalled for all parsing and compiling methods but not for lex()because there you usually only want the actual source tokenized.
- Template.newcontext(_vars=None, shared=False, locals=None)
- Create a new Context for this template. The varsprovided will be passed to the template. Per default the globalsare added to the context. If shared is set to True the datais passed as it to the context without adding the globals.
locals can be a dict of local variables for internal usage.
- Template.rootrender_func(_context)
- 这是低层的渲染函数。它接受一个必须由相同模板或兼容的模板的new_context() 创建的 Context 。这个渲染函数由编译器从模板代码产生,并返回一个生产 unicode 字符串的生成器。
如果模板代码中发生了异常,模板引擎不会重写异常而是直接传递原始的异常。事实上,这个函数只在 render() / generate() / stream()的调用里被调用。
- Template.blocks
- 一个块渲染函数的字典。其中的每个函数与 root_render_func() 的工作相同,并且有相同的限制。
注意
低层 API 是易碎的。未来的 Jinja2 的版本将不会试图以不向后兼容的方式修改它,而是在 Jinja2 核心的修改中表现出来。比如如果 Jinja2 在之后的版本中引入一个新的 AST 节点,它会由 parse() 返回。