Evaluation Context

The evaluation context (short eval context or eval ctx) is a new objectintroduced in Jinja 2.4 that makes it possible to activate and deactivatecompiled features at runtime.

Currently it is only used to enable and disable the automatic escaping butcan be used for extensions as well.

In previous Jinja versions filters and functions were marked asenvironment callables in order to check for the autoescape status from theenvironment. In new versions it’s encouraged to check the setting from theevaluation context instead.

Previous versions:

  1. @environmentfilter
  2. def filter(env, value):
  3. result = do_something(value)
  4. if env.autoescape:
  5. result = Markup(result)
  6. return result

In new versions you can either use a contextfilter() and access theevaluation context from the actual context, or use aevalcontextfilter() which directly passes the evaluation context tothe function:

  1. @contextfilter
  2. def filter(context, value):
  3. result = do_something(value)
  4. if context.eval_ctx.autoescape:
  5. result = Markup(result)
  6. return result
  7. @evalcontextfilter
  8. def filter(eval_ctx, value):
  9. result = do_something(value)
  10. if eval_ctx.autoescape:
  11. result = Markup(result)
  12. return result

The evaluation context must not be modified at runtime. Modificationsmust only happen with a nodes.EvalContextModifier andnodes.ScopedEvalContextModifier from an extension, not on theeval context object itself.

  • class jinja2.nodes.EvalContext(environment, template_name=None)
  • Holds evaluation time information. Custom attributes can be attachedto it in extensions.

    • autoescape
    • True or False depending on if autoescaping is active or not.

    • volatile

    • True if the compiler cannot evaluate some expressions at compiletime. At runtime this should always be False.