如何从Jinja2 contextfi访问For变量

2024-04-19 19:18:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Jinja2开发了一个基于以下过滤器的定制i18n系统(简化):

@contextfilter
def render(context, value):
    """
    Renders the filtered value as a string template, using the context
    and environment of the caller template.
    """
    mini_template = _environment.from_string(value)
    return mini_template.render(context)

例如,这允许我创建以下上下文:

^{pr2}$

在我的模板中使用它:

{{ greetings[user.locale]|render() }}

那很好用。在

现在假设我有一个用户数组,而不是单个用户。我在Django模板中执行了以下操作,但在Jinja2中不起作用,因为变量'user'不在上下文中:

{% for user in list_of_users %}
    {{ greetings[user.locale]|render() }}
{% endfor %}

我能做些什么来将新变量(user)添加到我在contextfilter中使用的上下文中吗?如果我想让它工作的话,我需要同时添加它的名称和值。在

非常感谢你的帮助。在


Tags: ofthe模板jinja2stringenvironmentvaluecontext
1条回答
网友
1楼 · 发布于 2024-04-19 19:18:49

好的,我已经用kwargs修复了它(尽管它比Django模板中的等价物更冗长)。在

过滤器:

@contextfilter
def render(context, value, **kwargs):
    """
    Renders the filtered value as a string template, using the context
    and environment of the caller template.
    """
    if kwargs:
        kwargs.update(context)
        ctx = kwargs
    else:
        ctx = context

    #we render the string as its own template
    mini_template = _environment.from_string(value)
    return mini_template.render(ctx)

用法:

^{pr2}$

相关问题 更多 >