How to Pass Variables to Template in Flask: Simple Guide
In Flask, you pass variables to templates by including them as keyword arguments in the
render_template function. These variables become accessible inside the template using their names as placeholders.Syntax
Use the render_template function to send variables from your Flask route to the HTML template. Pass variables as key=value pairs after the template filename.
template_name.html: The HTML file to render.key=value: Variables you want to use inside the template.
python
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): user = 'Alice' age = 30 return render_template('index.html', username=user, user_age=age)
Example
This example shows a Flask app passing two variables, username and user_age, to the index.html template. The template then displays these values dynamically.
python
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): username = 'Alice' user_age = 30 return render_template('index.html', username=username, user_age=user_age) # index.html content: # <!DOCTYPE html> # <html lang="en"> # <head><title>User Info</title></head> # <body> # <h1>Welcome, {{ username }}!</h1> # <p>Your age is {{ user_age }}.</p> # </body> # </html>
Output
<h1>Welcome, Alice!</h1>
<p>Your age is 30.</p>
Common Pitfalls
Common mistakes include:
- Not passing variables as keyword arguments to
render_template. - Using variable names in the template that do not match those passed from Flask.
- Forgetting to create or place the template file in the
templatesfolder.
Always ensure your template variables match exactly the names you pass in your route.
python
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): user = 'Alice' # Wrong: passing a dictionary instead of keyword arguments # return render_template('index.html', **{'username': user}) # Right: pass as keyword argument return render_template('index.html', username=user)
Quick Reference
| Step | Description | Example |
|---|---|---|
| 1 | Import render_template | from flask import render_template |
| 2 | Create variables in route | username = 'Alice' |
| 3 | Pass variables to template | render_template('index.html', username=username) |
| 4 | Use variables in template | {{ username }} |
Key Takeaways
Use render_template with keyword arguments to pass variables to templates.
Variable names in the template must match those passed from Flask exactly.
Place your HTML templates inside the 'templates' folder for Flask to find them.
Avoid passing variables as dictionaries; use keyword arguments instead.
Use double curly braces {{ variable }} in templates to display passed variables.