在使用 Flask 和 Jinja2 模板引擎时,如果你发现 Python 变量没有正确显示在 HTML 文件中,可能是由于以下几个原因:
templates
文件夹)。{{ }}
语法。my_flask_app/
app.py
templates/
index.html
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
my_variable = "Hello, World!"
return render_template('index.html', my_variable=my_variable)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask Jinja2 Example</title>
</head>
<body>
<h1>{{ my_variable }}</h1>
</body>
</html>
my_variable
在视图函数中被正确定义并传递。{{ my_variable }}
。index.html
文件位于 templates
文件夹内。render_template
中指定完整路径,例如 render_template('subfolder/index.html', my_variable=my_variable)
。通过以上步骤,你应该能够解决 Flask 和 Jinja2 中变量未显示的问题。如果问题仍然存在,建议检查 Flask 应用的配置和环境设置,确保所有组件都正确安装和配置。
领取专属 10元无门槛券
手把手带您无忧上云