I
I
Igor2020-10-09 12:59:59
Flask
Igor, 2020-10-09 12:59:59

How can I pass a value to base.html once to be displayed on the whole site in Flask?

Hello. I have base.html code.

<html>
    <head>
    </head>
    <header>Your balance: {{ balance }}</header>
<body> 
{% block content %}
{% endblock %}
</body>
</html>


and views.py

@app.route("/")
def index():
    balance = User.query.get(...)
    return render_template('index.html',
    balance = balance)

@app.route("/settings")
def settings():
    balance = User.query.get(...)
    return render_template('settings.html',
    balance = balance)

@app.route("/exchange")
def exchange():
    balance = User.query.get(...)
    return render_template('exchange.html',
    balance = balance)


etc., many pages. Where I pass the same thing in each function - balance.

{{ balance }} - it should be displayed on all pages where this base.html is included.

To do this, I need to pass a balance object to each function for each page. How can I make it so that I can only pass it once for all pages? Instead of writing balance in each function and passing it to the renderer? Since the user's balance should be shown on every page of the site with this base.html

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
ge, 2020-10-10
@gedev

The answer is found in the documentation. You can use context processors.
Functions and variables passed through the context processor become available in the template.
In the code below, the balance variable is passed through the get_balance() function. There is no need to change anything in the template. Note that both variables and functions are returned as a dictionary (dict()).
app.py:

from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.context_processor
def get_balance():
    balance = '10'
    return dict(balance=balance)

@app.route('/')
def index():
    return render_template('page.html')

if __name__ == '__main__':
    app.run()

E
Emil Revencu, 2020-10-10
@Revencu

@app.before_request
def before_request():
    g.balance = User.query.get(...)

In base.html use {{g.balance}}
Don't forget to include the g object in all templates
from flask import g

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question