深度阅读

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

作者
作者
2023年08月22日
更新时间
11.28 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。