python - 为什么 send_from_directory 在烧瓶中工作时 render_template 失败?
问题描述
我正在尝试修改以下代码库: https ://github.com/FloatingOctothorpe/python-kanban
当我更改 main.py 中的行时:
return send_from_directory('static', 'index.html')
至
return render_template('index.html')
我得到:
jinja2.exceptions.UndefinedError: 'card' is undefined
-- 我什至将静态文件夹重命名为模板。
这里发生了什么?
解决方案
不是它找不到您的模板,而是您必须{{card}}
在 html 文件中的某个地方使用过,而 jinja / python 无法找到该变量。
您必须在模板中的某处使用 {{card}}。检查它。
send_from_directory
这样做,按原样发送文件,它不会尝试将您的模板或 jinja 变量转换为它们的 html 文件。
使用 render_template 时,您必须将变量作为参数传入
IE
@mail.route("/home", methods=["GET", "POST"])
def home():
card = {"card":"birthday"}
return render_template('home.html', card=card)
还有其他将变量传递到模板的方法。
您可以添加一个可从模板中调用的模板函数
from flask import current_app
def get_card():
return {"card":"bierthday"}
current_app.jinja_env.globals.update(
get_card=get_card
)
然后在home.html
<html>
<body>
{{get_card()}}
</body>
</html>
推荐阅读
- python - 在驱动程序中作为 PySpark 依赖项添加的模块中的自动重新加载更改
- mysql - 非常慢的最小值分组查询
- python - Chainer 问题中的自动编码器
- android - Android:音频的最大音频会话数或效果引擎数?(EQ,REV...)
- c# - 在用户控件中找不到资源字典中的样式
- python - Keras:IndexError:元组索引超出范围 - Conv2D
- wpf - 如何在显示子内容时隐藏父控件?
- android - 无法从 SQLite 数据库中删除一些记录
- dart - Flutter - 关闭小部件时 BLoC 流实例会导致内存泄漏吗?
- docker - Docker 硬件虚拟化与 virtualbox vms 冲突