'Flask: How to pass values to base.html?

Some data needs to be present in all templates.

How can I transfer the data I need to base.html?

For normal templates I use the render() function.

I do not understand how to apply this for the base template, as it does not get passed into render()

base.html

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

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 ..

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

To do this, I need to pass a balance object in each function for each page. How can I make it so that I can only transfer it once for all pages?



Solution 1:[1]

The base.html file is meant to serve as a template for your other HTML files. You do not require to render it as a template from your app. Instead, you include base.html as an extension to your other HTML files.

There is no restriction is displaying variables in the base.html file. The below example should be of help.

base.html

<html>
    <head>
        <title>{{ title }}</title>
    </head>
<body> 

{% block content %}
 
{% endblock %}

</body>
</html>

index.html

{% extends "base.html" %}
{% block content %}
<h1>Homepage</h1>
{% endblock %}

app.py

from flask import Flask,render_template
app = Flask(__name__)

@app.route("/")
def index():
    title = "Homepage"
    
    return render_template('index.html',
    title = title)


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

Solution 2:[2]

I am late to answer but for the benefit of others I am adding this. flask context_processor would help. You can pass your function to the decorator anywhere in your file and then, you can call the function from any of your html templates.

@app.context_processor
def utility_processor():
    def format_price(amount, currency=u'€'):
        return u'{0:.2f}{1}'.format(amount, currency)
    return dict(format_price=format_price)

The context processor above makes the format_price function available to all templates:

The above function output can be called by {{ format_price(0.33) }} in your html file.

Official Document: https://flask.palletsprojects.com/en/1.1.x/templating/#context-processors

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sunil Nair
Solution 2 Moriartyalex