无法在jinja2宏中使用当前用户?

2024-04-25 21:00:30 发布

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

我使用Flask登录,它在模板中提供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)。

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


Tags: 对象代码form模板flaskifishtml

热门问题