小编典典

不能在jinja2宏中使用current_user?

flask

我使用Flask-Login current_user在模板中提供对象。我想编写一个宏来显示评论表单或登录链接,具体取决于用户是否登录。如果我直接在模板中使用此代码,它将起作用:

{% if current_user.is_authenticated %}
    {{ quick_form(form) }}
{% else %}
    <a href="{{ url_for('auth.login') }}">Log In with Github</a>
{% endif %}

我将相同的代码放在宏中,然后将宏导入模板中。

{% macro comment_form(form) %}
    {% if current_user.is_authenticated %}
        ...
    {% endif %}
{% endmacro %}
{% from "macros/comments.html" import comment_form %}
{% extends "base.html" %}
{% block content %}
    {# ... content goes here ... #}
    {{ comment_form(form) }}
{% endblock %}

当我尝试加载此页面时,出现的错误是:

jinja2.exceptions.UndefinedError: 'current_user' is undefined

当然,简单的解决方法是current_user作为参数传递并使用该参数(进行签名comment_form(user, form)),尽管这是一个非常丑陋的解决方案(imo)。

宏为什么不使用上下文处理器?它不包含上下文吗?


阅读 747

收藏
2020-04-08

共1个答案

小编典典

没错,你不需要将上下文作为宏的参数。你可以导入宏with context,它们将可以访问其导入模板的上下文。

{% from "macros/comments.html" import comment_form with context %}
2020-04-08