问题
I want to access variables in the jinja2 macro namespace inside a contextfunction. Say my macro looks like:
{% macro show_var(a) %}
{{ show_var_context_function("a") }}
{% endmacro %}
and my contextfunction looks like this:
@contextfunction
def show_var_context_function(context, var_name_string):
return context[var_name_string]
Now I think context should have access to a... this should be stored within the context I would think, but the above code will raise a NameError on a, saying it isn't defined within context. I wonder if this is because the context is supposed to be the context of the template and not the macro?
Anyways, is there any way to access the context of the macro?
回答1:
It sounds like you're tying to access your global Jinja context from within a macro namespace. To do this, you must import your macros to each of your templates "with context".
{% from "_macros.html" import my_macro with context %}
来源:https://stackoverflow.com/questions/49517615/access-macro-context-in-jinja2