python - 将 Flask 模板扩展到模块文件夹之外

标签 python flask jinja2

由于某种原因,我无法扩展我的 base.html 模板。

我的应用程序结构

-app
|-- main
|     |-- __init__.py
|     |-- views.py
|-- templates
|     |-- main
|     |    |-home.html
|     |-- base.html

我的应用程序/main/views.py

from flask import (
Blueprint,
render_template
)

main_blueprint = Blueprint('main', 
                          __name__, 
                          template_folder='../templates/main'
                          )


@main_blueprint.route('/')
def index():
    return render_template('index.html') 

我的应用程序/模板/base.html

<html> ...
  {% block content %}
  {% endblock %}      
</html>

我的应用程序/templates/main/index.html

{% extends 'base.html' %}
{% block content %}
    <h1>Testing</h1>
{% endblock %}

当我尝试运行该应用程序时,出现错误:

jinja2.exceptions.TemplateNotFound: base.html

知道我做错了什么吗?

最佳答案

快速修复使其工作:在创建应用实例时使用 Flask(__name__, template_folder="../templates")

如果您没有显式传递flask应用程序的template_folder,它将在同一目录中查找templates。在您的情况下,它正在主文件夹下查找,并且 Flask 无法找到任何模板。有一些很好的自以为是的方法来构建 Flask 应用程序代码。请研究它们并决定哪个适合您。

关于python - 将 Flask 模板扩展到模块文件夹之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59109562/

相关文章:

python - 如何在 Python Flask 的 celery 任务中保留请求上下文?

python - Flask - 在 Ajax/JQuery 中无需重定向即可更新页面内容

python - PRAW:使用 OAuth 授权会阻止我获得提交/评论

python - 如何从 python 中的时间序列数据创建监督学习数据集

python - 为什么 scipy.special.hankel1(0, 10**10) 返回 `nan` ?

python - Flask 在使用蓝图静态路由时为蓝图静态文件引发 404

python - 如何使用不同的配置安装OpenCV?

python - 使用 FieldList 在 WTForm 的选择字段中动态分配选项

python - 如何在jinja2中重新定义宏

ansible - 使用 ansible playbook 检查嵌套数据结构中的给定字符串