Skip to content

Passing Data to Your Template

So far, render_template('index.html') just sends the HTML file as-is. The page is static — the same every time, no matter what is happening in Python.

But Flask lets you pass data from your Python code directly into the HTML. A list, a dictionary, a number, a name — whatever you have in Python can appear on the page. This is where the backend and frontend really start talking to each other.


The idea

In app.py, you have a list of people:

people = [
    {"name": "Alice", "age": 24, "gender": 1},
    {"name": "Bob",   "age": 31, "gender": 2},
    {"name": "Carol", "age": 19, "gender": 1},
]

You want that list to show up in your HTML page. You do that by passing it into render_template:

return render_template('index.html', people=people)

The people=people part is the handover. On the left is the name the template will use. On the right is the Python variable. The template gets a copy of the list and can do things with it.


The full app.py

from flask import Flask, render_template

app = Flask(__name__)

people = [
    {"name": "Alice", "age": 24, "gender": 1},
    {"name": "Bob",   "age": 31, "gender": 2},
    {"name": "Carol", "age": 19, "gender": 1},
]

@app.route('/')
def home():
    return render_template('index.html', people=people)

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

What is Jinja2?

The bridge between your Python data and your HTML is called Jinja2 — it is the template engine Flask uses. It lets you write special tags inside your HTML that Flask fills in before sending the page to the browser.

There are two things you will use:

  • {{ something }} — print a value onto the page
  • {% ... %} — run logic (like a loop or an if statement)

Think of them as Python, but written inside HTML. They look different so the browser does not confuse them with normal HTML.


Printing a single value

In templates/index.html, you can now use {{ people }} anywhere in the body:

<body>
    <p>{{ people }}</p>
</body>

Run the app and visit http://127.0.0.1:5000. You will see the raw Python list printed on the page. Not pretty yet — but it proves the data arrived.


Challenge

Add the people list to app.py and pass it to render_template. In index.html, add <p>{{ people }}</p> somewhere in the body. Run the app and confirm you can see the list on the page.

Once you see it — even as raw text — the connection is working. The next page shows you how to display it properly.


← Your First Flask App    Next: Looping in Your Template →