如果希望向HTML页面传递参数,可以在函数中申明一个变量,然后使用render_template()函数传递过去。在render_template()函数中将视图函数中的变量赋值给HTML页面中的变量。然后通过模板渲染,就实现传值。
如下所示:
@app.route('/hello.html')
def hello_world():
args = request.args # 获取所有参数
name =args.get('name')
return render_template('hello.html',name=name)
说明:render_template()中参数名name,指的是模板HTML页面中变量名,值name为在视图函数中定义的变量名,可以命名一样,如:
@form.route('/formplay') #在蓝图对象上进行操作,路由
def index():
# 往模板中传入的数据
my_str11 = 'Hello Word22'
my_int = 10
my_array = [3, 4, 2, 1, 7, 9]
my_dict = {
'name': 'xiaoming',
'age': 18
}
return render_template('hello.html',
my_str=my_str,
my_int=my_int,
my_array=my_array,
my_dict=my_dict
)
备注:也可以命名不一样。如下变量my_str22为html页面中的变量名,my_str11为视图函数中定义的变量名,将视图函数中的变量赋值给HTML页面中的变量。
@form.route('/formplay') #在蓝图对象上进行操作,路由
def index():
# 往模板中传入的数据
my_str11 = 'Hello Word22'
my_int = 10
my_array = [3, 4, 2, 1, 7, 9]
my_dict = {
'name': 'xiaoming',
'age': 18
}
return render_template('hello.html',
my_str22=my_str11,
my_int=my_int,
my_array=my_array,
my_dict=my_dict
)



