tobltobs
tobltobs

Reputation: 2929

How to set a variable in the flask context from a jinja macro?

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.

Upvotes: 5

Views: 1992

Answers (1)

Daniel Himmelstein
Daniel Himmelstein

Reputation: 1909

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.

Upvotes: 2

Related Questions