为什么 {% load static %} 是 {% get_media_prefix %} 的依赖项?

Why is {% load static %} a dependency for {% get_media_prefix %}?

我已经使用 {% get_media_prefix %} 很长时间了。当他指出这一点时,我正在向某人解释这一点。

为什么要声明{% load static %}才能使用?

它甚至在文档的示例代码中使用 here

在某种程度上,我理解静态文件和媒体文件在本质上是相似的。即使我们将它们与 nginx+gunicorn 组合使用,nginx 也会处理它们(我们让其他一切代理,但不让这些代理)。

但是 我们仍然为这些文件定义了单独的 MEDIA_URLSTATIC_URL 以及 MEDIA_ROOTSTATIC_ROOT .

那为什么要声明 {% load static %} 才能使用 {% get_media_prefix %} 呢?

提前致谢。

为了在您的 HTML 中使用模板标签,您必须首先 load 包含它的模块。

因此,根据 source code of get_media_prefix template tag,此模板标签位于 django/templatetags/static.py

这就是为什么您每次在每个 HTML 模板中使用它时都必须 load 的原因。

这当然适用于所有模板标签的使用。在每个 HTML 文件的顶部加载模板标签,然后使用它们。就像你 import 你 python 代码中的一个函数。

更新:来自 Django 1.3 release notes

In previous versions of Django, it was common to place static assets in MEDIA_ROOT along with user-uploaded files, and serve them both at MEDIA_URL. Part of the purpose of introducing the staticfiles app is to make it easier to keep static files separate from user-uploaded files. Static assets should now go in static/ subdirectories of your apps or in other static assets directories listed in STATICFILES_DIRS, and will be served at STATIC_URL.

如您所见,Django 过去对静态和媒体一视同仁。从 Django 1.3 开始这个改变了,但是模板标签没有。没什么大不了的。这只是一个约定。