。在Flask中,可以通过使用render_template
函数来渲染模板并传递变量。首先,需要在Flask应用程序中导入render_template
函数:
from flask import Flask, render_template
然后,可以定义一个路由来处理请求并渲染模板。在路由函数中,可以将变量作为参数传递给render_template
函数,并在模板中使用该变量:
@app.route('/')
def index():
variable = "Hello, Flask!"
return render_template('index.html', variable=variable)
在上面的例子中,variable
是一个字符串变量,它被传递给名为index.html
的模板。在模板中,可以使用{{ variable }}
语法来引用该变量:
<!DOCTYPE html>
<html>
<head>
<title>Flask Variable Example</title>
</head>
<body>
<h1>{{ variable }}</h1>
</body>
</html>
当用户访问根URL时,Flask将调用index
函数并渲染index.html
模板。在模板中,{{ variable }}
将被替换为Hello, Flask!
。
推荐的腾讯云相关产品:腾讯云云服务器(CVM),产品介绍链接地址:https://cloud.tencent.com/product/cvm
领取专属 10元无门槛券
手把手带您无忧上云