在Jinja2中访问宏上下文 [英] Access Macro Context in Jinja2

查看:50
本文介绍了在Jinja2中访问宏上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问contextfunction内jinja2宏命名空间中的变量.说我的宏看起来像:

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 %}

和我的contextfunction看起来像这样:

and my contextfunction looks like this:

@contextfunction
def show_var_context_function(context, var_name_string):
  return context[var_name_string]

现在,我认为上下文应该可以访问a ...应该将其存储在我认为的上下文中,但是上面的代码将在a上引发NameError,表示它不是在上下文中定义的.我想知道这是否是因为上下文应该是模板的上下文,而不是宏?

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?

推荐答案

听起来您想从宏命名空间访问全局Jinja上下文.为此,必须将宏带有上下文"导入到每个模板.

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 %}

这篇关于在Jinja2中访问宏上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆