5

I would like to create a macro which needs to keep track if it was ever called before. Therefore I would have to set a variable in the request context in my macro, but I don't have an idea how I could do that. Something like:

{% macro my_macro() -%}
    {% set g.foo = "bar" %}   <-- Error
    {{ g.get('foo') }}
{%- endmacro %}

The above results in an jinja2.exceptions.TemplateRuntimeError: cannot assign attribute on non-namespace object error.

I am aware that this might be an abuse of the macro concept and would also be open for other solutions. I want to keep track of the macro use, so I can output some required javascript for the macro at most one time, or not at all if the macro wasn't used.

JHS
  • 1,423
  • 17
  • 29
tobltobs
  • 2,782
  • 1
  • 27
  • 33

1 Answers1

2

There is a workaround to use a do rather than set command:

{% do g.update({"foo": "bar"}) %}

Note that the do command is not enabled by default, so for this to work you must enable jinja2.ext.do as described here.

Daniel Himmelstein
  • 1,759
  • 1
  • 21
  • 26