🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
求值上下文(缩写为 eval context 或 eval ctx )是 Jinja 2.4 中引入的新对象, 并可以在运行时激活/停用已编译的特性。 当前它只用于启用和禁用自动转义,但也可以用于扩展。 在之前的 Jinja 版本中,过滤器和函数被标记为环境可调用的来从环境中检查自动 转义的状态。在新版本中鼓励通过求值上下文来检查这个设定。 之前的版本: ~~~ @environmentfilter def filter(env, value): result = do_something(value) if env.autoescape: result = Markup(result) return result ~~~ 在新版本中,你可以用 [contextfilter()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.contextfilter "jinja2.contextfilter") 从实际的上下文中访问求值上下 文,或用[evalcontextfilter()](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.evalcontextfilter "jinja2.evalcontextfilter") 直接把求值上下文传递给函数: ~~~ @contextfilter def filter(context, value): result = do_something(value) if context.eval_ctx.autoescape: result = Markup(result) return result @evalcontextfilter def filter(eval_ctx, value): result = do_something(value) if eval_ctx.autoescape: result = Markup(result) return result ~~~ 求值上下文一定不能在运行时修改。修改只能在扩展中的 用 [nodes.EvalContextModifier](http://docs.jinkan.org/docs/jinja2/extensions.html#jinja2.nodes.EvalContextModifier "jinja2.nodes.EvalContextModifier") 和[nodes.ScopedEvalContextModifier](http://docs.jinkan.org/docs/jinja2/extensions.html#jinja2.nodes.ScopedEvalContextModifier "jinja2.nodes.ScopedEvalContextModifier") 发生,而不是通过求值上下文对 象本身。 *class *jinja2.nodes.EvalContext(*environment*, *template_name=None*)[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.nodes.EvalContext "Permalink to this definition") Holds evaluation time information. Custom attributes can be attached to it in extensions. autoescape[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.EvalContext.autoescape "Permalink to this definition") True 或 False 取决于自动转义是否激活。 volatile[](http://docs.jinkan.org/docs/jinja2/api.html#jinja2.EvalContext.volatile "Permalink to this definition") 如果编译器不能在编译期求出某些表达式的值,为 True 。在运行时应该 始终为False 。