Answer the question
In order to leave comments, you need to log in
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>
@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)
Answer the question
In order to leave comments, you need to log in
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()
@app.before_request
def before_request():
g.balance = User.query.get(...)
from flask import g
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question