如何理解 Django 模板?

How to understand Django templates?

这里是 Django 官方教程,模板部分:

First, create a directory called templates in your polls directory. Django will look for templates in there.

Within the templates directory you have just created, create another directory called polls, and within that create a file called index.html. In other words, your template should be at polls/templates/polls/index.html. Because of how the app_directories template loader works as described above, you can refer to this template within Django simply as polls/index.html.

...以及 "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.

但是不同的应用有不同的templates目录的绝对路径。这样的项目结构有什么问题吗?

my_project
    |
    +--first_app
    |       |
    |       +--templates
    |             |
    |             +--index.html
    |             +--foo.html
    +--second_app
            |
            +---templates
                  |
                  +index.html

我们有 my_project/first_app/templates/index.html 和 my_project/second_app/templates/index.html - 无碰撞。

Django will choose the first template it finds whose name matches

我想,Django 使用相对路径来比较绝对路径。这有什么意义呢?有没有隐藏利润?

我刚开始研究 Django,这似乎违反了 DRY 原则。那么,为什么如此优雅的pythonic框架使用如此奇怪的约定?

templates/ 下的所有内容都归为一个列表。它们是 "put over one another" 按照您的 INSTALLED_APPS 设置的顺序(从最底部开始)。

在你的例子中,如果 INSTALLED_APPS = ['first_app', 'second_app'],django 将知道两个模板:

  • index.html 来自 first_app,它覆盖了来自 second_app 的 similary-named。

  • foo.html 来自 first_app.

所以...在您的每个应用程序 中 templates/ 以下的所有内容都组合在一起。这就是为什么最好使用文档中提到的命名空间。所以 second_app/templates/second_app/index.html,例如

Django 允许您覆盖模板非常方便:例如,您可以覆盖默认登录页面。