Django:有没有办法在嵌套文件夹中加载模板?

2024-04-24 23:34:42 发布

您现在位置:Python中文网/ 问答频道 /正文

在这一刻,我有一个应用程序,有超过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

问题:是否有方法从模板文件夹中的文件夹加载模板,或者所有模板都必须位于模板文件夹中?你知道吗


Tags: 文件文件夹模板app应用程序htmlcomponentstemplates
1条回答
网友
1楼 · 发布于 2024-04-24 23:34:42

是的,这是可能的,你唯一要确定的是你的设置.py还有你的观点。你知道吗

设置.py:

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

只需链接到folder/*.html,如上的下面示例视图.py

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

相关问题 更多 >