我看到有两种方法可以在项目中构建模板。模板可以存储在蓝图中的 templates/ 文件夹中,或者每个蓝图在全局模板文件夹中都有一个文件夹。两者有什么区别?为什么我应该使用一个?

app/
    blueprint1/
        __init__.py
        views.py
        templates/
    blueprint2/
        __init__.py
        views.py
        templates/
    templates/  # Global templates folder
app/
    blueprint1/
        __init__.py
        views.py
    blueprint2/
        __init__.py
        views.py
    templates/  # Global templates folder
        blueprint1/
        blueprint2/

最佳答案

就 Flask 所见而言,两者是等效的,它的 Jinja 加载器结合了蓝图和全局文件夹。蓝图模板被视为默认源,全局源会覆盖这些源。通常,蓝图模板仅在您编写其他人将安装和覆盖的扩展时才有用,如果您只是在内部使用它们,则它不会提供任何内容。请注意,您需要在蓝图和全局文件夹中使用相同的文件夹结构,否则您将看到意外冲突,因为加载程序直接覆盖文件夹,而不是按蓝图名称。

project/
    package/
        __init__.py
        blueprint1/
            __init__.py
            templates/
                blueprint1/
                    page.html  # default
        templates/
            blueprint1/
                page.html  # overrides blueprint

关于python - 模板应该在蓝图模板文件夹还是全局模板文件夹中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33106143/

10-14 19:23
查看更多