Skip to content

Passing Variables to Templates

Templates become powerful when you pass data to them.

Passing variables from Flask

python
from flask import Flask, render_template
 
app = Flask(__name__)
 
 
@app.route("/hello/<name>")
def hello(name):
    return render_template("hello.html", name=name)
python
from flask import Flask, render_template
 
app = Flask(__name__)
 
 
@app.route("/hello/<name>")
def hello(name):
    return render_template("hello.html", name=name)

Template templates/hello.htmltemplates/hello.html:

html
<!doctype html>
<html>
  <body>
    <h1>Hello, {{ name }}!</h1>
  </body>
</html>
html
<!doctype html>
<html>
  <body>
    <h1>Hello, {{ name }}!</h1>
  </body>
</html>

Passing dictionaries and lists

python
@app.route("/users")
def users():
    data = [
        {"username": "ravi", "role": "admin"},
        {"username": "alex", "role": "user"},
    ]
    return render_template("users.html", users=data)
python
@app.route("/users")
def users():
    data = [
        {"username": "ravi", "role": "admin"},
        {"username": "alex", "role": "user"},
    ]
    return render_template("users.html", users=data)

In Jinja you can access:

  • {{ user.username }}{{ user.username }} or {{ user['username'] }}{{ user['username'] }}

Good practice

  • Keep templates focused on presentation.
  • Do validation/computation in Python, then pass already-clean data to the template.

This makes templates simpler and safer.

🧪 Try It Yourself

Exercise 1 – Create a Flask App

Exercise 2 – Dynamic Route

Exercise 3 – Return JSON

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did