Pass Variable from Python to HTML Template in Flask

Flask – Pass variable from Python to HTML template

In a flask application, we can pass variables from Python code in flask application to HTML template for rendering.

The following is a simple code snippet to pass variable named title to render page-1 template function.

@app.route("/hello-world")
def hello_world():
    return render_template("page-1.html", title="Hello World")

Variables are passed from Python code to HTML files as key-value pairs in render_template() function.

Example

In this example, we build a flask application where we have following project structure.

Pass Variable from Python to HTML Template in Flask

When a request comes for /hello-world, we will render the template page-1.html and pass the variable title to the page-1.html template and use that title variable in Heading 1.

main.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/hello-world")
def hello_world():
    return render_template("page-1.html", title="Hello World")

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)

page-1.html

{% include "header.html" %}

<h1>{{title}}</h1>
<h2>About</h2>
<p>Welcome to sample flask application.</p>

{% include "footer.html" %}

Run Application

Open terminal or command prompt at the root of the application, and run the Python file main.py.

Pass Variable from Python to HTML Template in Flask

The flask application is up and running at URL http://127.0.0.1:8080.

Now, open a browser of your choice and hit the URL http://127.0.0.1:8080/hello-world.

Flask - Pass variable from Python code to HTML template

Thus we can pass variables from Python code to HTML templates and dynamically render the data.

Project ZIP

Summary

In this Python Flask Tutorial, we learned how to pass variables from Python code to HTML templates, with the help of an example flask application.

Related Tutorials

Code copied to clipboard successfully 👍