【问题标题】:Django: is there a way to load templates in nested folders?Django:有没有办法在嵌套文件夹中加载模板?
【发布时间】:2018-01-05 02:21:51
【问题描述】:

此时我有一个应用程序,其中包含 100 多个这样的模板文件:

-app/
--templates/
---template1.html
---template2.html
--- ...
---template100.html

但我想将这些文件分隔在一些文件夹中,如下所示:

-app/
--templates/
---masters/
----master1.html
----master2.html
---components/
----component1.html
----component2.html
---others/
----other1.html
----other2.html

问题:有没有办法从模板文件夹内的文件夹中加载模板,或者所有模板都必须位于模板文件夹中?

【问题讨论】:

    标签: python django templates django-templates


    【解决方案1】:

    是的,这是可能的,您唯一需要确保检查的是您的 settings.py 和您的视图。

    settings.py:

    TEMPLATES = [
        {
            ...
            'DIRS': [os.path.join(
                BASE_DIR,
                'yourapp/templates',
                #'yourapp/templates/componements', avoid to refactor each view
                #'yourapp/templates/masters',
                ... etc ...
            )],
            ...
        },
    ]
    

    只需链接到folder/*.html,就像您的 views.py 上的以下示例一样:

    ...
    return render(request, 'componements/componement1.html', {...})
    #return render(request, 'componement1.html', {...}), no refactor solution
    

    【讨论】:

    • 我刚刚做了一些测试,这确实有效,这个解决方案的主要问题是我必须重构数百个渲染函数。感谢您的回答,如果这个问题在没有重构的情况下无法以“动态”方式完成,那么我将在 24 小时内接受您的回答。
    • 如何更新设置'DIRS'并添加'yourapp/template/componements'
    • 天啊,我很遗憾在阅读您的答案后没有考虑这种方法。谢谢你。我会接受你的回答。
    • 你知道是否可以让它更加动态,比如:'yourapp/templates/*'。
    • @Nazkter 从未尝试过但可能确实有效,我会让你做一些测试:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 2017-12-20
    • 1970-01-01
    • 2022-01-24
    • 2013-10-11
    • 2022-01-05
    相关资源
    最近更新 更多