Access Macro Context in Jinja2

梦想的初衷 提交于 2021-01-28 11:30:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!