在jinja2宏中不能使用current_user? [英] cannot use current_user in jinja2 macro?

查看:357
本文介绍了在jinja2宏中不能使用current_user?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Flask-Login在模板中提供 current_user 对象。我想写一个宏来显示一个注释表单或一个登录链接,取决于用户是否登录。如果我直接在模板中使用这个代码,它的工作原理:

{%if current_user.is_authenticated%}
{{quick_form(form)}}
{%else%}
< a href ={{url_for('auth.login')}}>使用Github登录< / a>
{%endif%}

我在宏中放置了相同的代码,在我的模板中。
$ b

  {%macro comment_form(form)%} 
{ if current_user.is_authenticated%}
...
{%endif%}
{%endmacro%}



{%frommacros / comments.htmlimport comment_form%}
{%extendsbase。 html%}
{%block content%}
{#... content goes here ...#}
{{comment_form(form)}}
{%endblock %}

当我尝试加载这个页面时,我得到的错误是:

  jinja2.exceptions.UndefinedError:'current_user'is undefined 

当然,简单的解决方法是传入 current_user 作为参数并使用它(使签名 comment_form (user,form)),虽然这是一个相当丑陋的解决方案(imo)。

为什么宏不使用上下文处理器?它不是持有上下文吗?

解决方案

模板呈现的上下文不传递给导入,除非指示这样做。请参阅相关文档



你是对的,你不需要将上下文作为参数注入宏。您可以使用上下文导入宏,并且可以访问导入的模板上下文。



< pre class =lang-html prettyprint-override> {%frommacros / comments.htmlimport comment_form with context%}


I use Flask-Login which provides the current_user object in templates. I want to write a macro to show a comment form or a log in link depending on if the user is logged in. If I use this code directly in the template, it works:

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

I placed the same code in a macro and import the macro in my template.

{% 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 %}

When I try to load this page, the error I get is:

jinja2.exceptions.UndefinedError: 'current_user' is undefined

Of course, the easy workaround is to pass in current_user as a parameter and use that (making the signature comment_form(user, form)), although this is a fairly ugly solution (imo).

Why doesn't the macro use the context processor? Does it not hold the context?

解决方案

The context a template is rendered in is not passed to imports unless instructed to do so. See the relevant docs.

You're right, you don't need to inject context as arguments to macros. You can import the macros with context and they will have access the the context of the template they're imported in.

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

这篇关于在jinja2宏中不能使用current_user?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆