嵌套模板目录结构的原因是什么?

2024-04-25 23:35:35 发布

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

django template文件夹requires创建一个子文件夹,该子文件夹使用应用程序的名称,然后包含模板文件。当python manage.py collectstatic可以在遍历所有目录时推断出此信息时,为什么需要这样做?这似乎很多余。在


Tags: 文件djangopy目录文件夹名称模板信息
1条回答
网友
1楼 · 发布于 2024-04-25 23:35:35

首先,Django不需要这个特定的文件夹结构来工作,它只是一个既定的模式。当然,正如official doc所指出的那样,它有一个基本原理:

Template namespacing

Now we might be able to get away with putting our templates directly in polls/templates (rather than creating another polls subdirectory), but it would actually be a bad idea. Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself.

对于具体情况,可以引用this questionthat another。在

简而言之,通过遵循此模式,您可以将模板分为两组:

  1. 与特定站点或项目相关的模板可以位于TEMPLATES['DIRS']设置所指向的目录中
  2. 与特定应用程序相关的模板,如果你使你的应用程序可插拔,那么这些模板应该位于'./appname/templates/appname/'(并且TEMPLATES['APP_DIRS']必须为真)。这样可以避免文件夹内文件和外部文件之间的名称冲突。在

相关问题 更多 >