It is necessary to transfer the variable from jinja2 to the base template. If the call to the test function on python occurs via url, then everything works correctly. But it is necessary to call the send_user_login_status function with any change in the url. In this case, it does not work. How to make it so that the function send_user_login_status worked on any change in the url and sent variables using jinja2. The flask framework is used.

base.html - base template

<li class="{{ login_status_class }}"> {{ login_status }}</li> 

test.html - test page

 {% extends "base.html" %} 

Python function - works

 @app.route('/test') def test_api(): login_status_class = 'login' login_status = u'Enter' return render_template("base.html", login_status=login_status, login_status_class=login_status_class) 

Python function - not working

 def send_user_login_status(): login_status_class = 'login' login_status = u'Enter' return render_template("base.html", login_status=login_status, login_status_class=login_status_class) 

    1 answer 1

    How to make it so that the function send_user_login_status worked on any change in the url and sent variables using jinja2.

    You can use the decorator @ app.url_value_preprocessor, which will launch the desired function immediately after the formation of the request. And the necessary variables can be passed through g.

     from flask import Flask, render_template, g app = Flask(__name__) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def test(path): return render_template("base.html", login_status=g.login_status, login_status_class=g.login_status_class) @app.url_value_preprocessor def send_user_login_status(endpoint, values): g.login_status_class = u'login' g.login_status = u'Enter' if __name__ == '__main__': app.run(debug=True) 

    Read more here: Using URL Processors .

    • In this case, code duplication occurs. Do not tell me how to avoid it? ru.stackoverflow.com/questions/786374/… - lipton_v
    • @lipton_v, do you mean passing values ​​to a template? You can get the values ​​directly from the template: <li class = "{{g.login_status_class}}"> {{g.login_status}} </ li> . Then the test function will return only: return render_template ("base.html") . - dodd0ro
    • To be honest, I don’t understand why to call the function send_user_login_status on every request, if you can check the status once during authorization and transfer it to flask.session. - dodd0ro