【发布时间】:2014-12-07 23:51:21
【问题描述】:
我使用 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)。
为什么宏不使用上下文处理器?它不包含上下文吗?
【问题讨论】: