cannot use current_user in jinja2 macro?

前端 未结 3 1618
梦毁少年i
梦毁少年i 2021-02-13 23:06

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 l

相关标签:
3条回答
  • 2021-02-13 23:47

    UPDATE: This is an incorrect answer according to OP's requirements.

    According to jinja2 docs not every variable is available in jinja2 macros. Change your macro and send ’current_user’ as a parameter to it:

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

    and this is how your will use it:

    {% from "macros/comments.html" import comment_form %}
    {% extends "base.html" %}
    {% block content %}
      {# ... content goes here ... #}
      {{ comment_form(form, current_user) }}
    {% endblock %}
    
    0 讨论(0)
  • 2021-02-13 23:49

    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 %}
    
    0 讨论(0)
  • 2021-02-14 00:10

    The current_user.is_authenticated is now accessed as a property and calling the method definition will lead to problems with more up-to-date library versions.

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

    0 讨论(0)
提交回复
热议问题