Skip to content

Passing Variables to Templates

Templates become powerful when you pass data to them.

Passing variables from Flask

from flask import Flask, render_template
 
app = Flask(__name__)
 
 
@app.route("/hello/<name>")
def hello(name):
    return render_template("hello.html", name=name)
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:

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

Passing dictionaries and lists

@app.route("/users")
def users():
    data = [
        {"username": "ravi", "role": "admin"},
        {"username": "alex", "role": "user"},
    ]
    return render_template("users.html", users=data)
@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