首页 > 解决方案 > 为什么 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-- 我什至将静态文件夹重命名为模板。

这里发生了什么?

标签: pythonflask

解决方案


不是它找不到您的模板,而是您必须{{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>

推荐阅读