Skip to main content
 首页 » 编程设计

python之Flask:在另一个文件夹中提供模板( 'templates/' 目录除外)

2024年10月01日7lonelyxmas

我已将项目的 sphinx 文档生成到文档文件夹中。现在我想使用 flask 服务器来提供服务。

这是我的项目结构。我想从文档文件夹中提供 example.html。该文件夹还包含它所需的相关 CSS 文件。

app/ 
    module1/ 
    module2/ 
    documentation/ 
        build/ 
            example.html 
            styles.css 
            ... 
    templates/ 
        other_files.html 
        ... 

app_controller.py
@application.route("/doc", methods=["GET"]) 
@log_exceptions_to_github 
def doc(): 
    return render_template('/build/index.html') 

问题:

默认情况下,Flask 仅在“templates”文件夹中查找 HTML 文件。

所以我不能提供这个服务。请注意,由于项目要求,从文档目录复制到模板目录不是我想要做的。

我想将“文档”文件夹添加为模板目录以及默认文件夹。

我已经试过了,但是没有用: https://stackoverflow.com/a/13598839/2286762

请您参考如下方法:

查看关于 how to organize templates 的 Flask 文档在 Flask 中。

那么为什么不简单地将您的 documentation 目录放在 templates 目录下,如下所示:

templates/ 
    index.html 
    documentation/ 
        build/ 
            example.html 
    other_directories/ 

然后只需调用return render_template('documentation/build/example.html')

如果你真的想保持你在代码示例中建议的结构,你可以看看关于 How to load from more then one template_folder for Flask blueprint? 的问题。 .

在 Flask 文档中,您可以找到更多关于 what is a blueprint 的信息.