【问题标题】:cannot use current_user in jinja2 macro?不能在 jinja2 宏中使用 current_user?
【发布时间】: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)。

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

【问题讨论】:

    标签: python flask jinja2


    【解决方案1】:

    除非指示这样做,否则不会将呈现模板的上下文传递给导入。请参阅relevant docs

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

    {% from "macros/comments.html" import comment_form with context %}
    

    【讨论】:

      【解决方案2】:

      current_user.is_authenticated 现在作为属性访问,调用方法定义将导致更新库版本出现问题。

      见: https://flask-login.readthedocs.org/en/latest/#flask.ext.login.current_user

      【讨论】:

        【解决方案3】:

        更新:根据 OP 的要求,这是一个不正确的答案。

        根据jinja2 docs,并非每个变量都在 jinja2 宏中可用。更改您的宏并将“current_user”作为参数发送给它:

        % macro comment_form(form, current_user, disabled=False) %}
        {% if current_user.is_authenticated() %}
          {{ quick_form(form) }}
        {% else %}
          <p class="text-muted">You are not signed in. Please <a href="{{ url_for('auth.login') }}">Sign In With Github</a> to continue
          </p>
        {% endif %}
        {% endmacro %}
        

        这就是你将如何使用它:

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

        【讨论】:

          猜你喜欢
          • 2012-12-06
          • 1970-01-01
          • 1970-01-01
          • 2012-12-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-07
          相关资源
          最近更新 更多