pythonjinja2

When are Jinja2 {% set %} operations actually run?


Is it safe to assume that if a portion of a template is not included due to conditional operations, {% set %} operations within it are not evaluated? For example:

{% if var = 1 %}
   {% set thing = function_with_side_effects() %}
{% endif

Is it safe to assume that if var != 1, function_with_side_effects() will never be called during expansion of this template?


Solution

  • Jinja templates evaluate to a Python AST (literal text evaluates to code that adds that text to output, etc). Normal/"real" flow control rules apply: code positioned anywhere in that AST runs the same way it would if it were created by Python code itself, vs an engine creating equivalent syntax trees.

    Thus, set operations are subject to flow control just as everything else is.