How to pass parameters from a Flask route function to a template

Published on Aug. 22, 2023, 12:16 p.m.

To pass parameters from a Flask route function to a template, you can use the render_template function provided by Flask. Here’s an example:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    my_list = ['item1', 'item2', 'item3']
    my_dict = {'key1': 'value1', 'key2': 'value2'}
    return render_template('index.html', my_list=my_list, my_dict=my_dict)

In this example, we define a route function called index that returns a rendered template called 'index.html'. We also create two variables - my_list and my_dict - that we want to pass to the template.

To pass these variables to the template, we use the render_template function and include the variable names and values as keyword arguments. In this case, we’re passing my_list and my_dict to the template under the variable names of the same name.

We can then use these variables in the template using Jinja2 syntax, as described in my previous response.

Note that the HTML template needs to be placed in a templates folder in the same directory as the Python file running the Flask app.

Tags: