{%load staticfiles%}和{%load static%}之间有什么区别?

tri*_*eta 88 django django-templates

问题中最重要的部分是主题.

我想知道哪种标签最适合哪种情况.而且......我找到了代码,它也settings.STATIC_URL包含{{STATIC_URL}}在模板中.

我有点困惑.

Nic*_*ick 58

内置static模板标记 "链接[s]到保存在STATIC_ROOT"的静态文件.

staticfiles的contrib应用程序的static模板标签 "使用配置的STATICFILES_STORAGE存储来为给定的相对路径的完整URL","使用非本地存储后端部署文件时特别有用",这是.

内置static模板标记的文档(链接到上面)有一个注释,说明使用staticfilescontrib app的static模板标记"如果你有一个高级用例,例如使用云服务来提供静态文件",它给出了这个例子这样做:

{% load static from staticfiles %}
<img src="{% static "images/hi.jpg" %}" alt="Hi!" />
Run Code Online (Sandbox Code Playgroud)

您可以使用{% load staticfiles %}而不是{% load static from staticfiles %}根据需要使用,但后者更明确.

  • [Django V1.10](https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#static)现在只推荐`{%load static%}`."在旧版本中,您必须在模板中使用`{%load static from staticfiles%}`来提供STATICFILES_STORAGE中定义的存储中的文件.这不再是必需的." (27认同)
  • 从 2016 年开始我们只需要使用 `{% load static %}`。 (2认同)

Del*_*eet 5

我不知道应该有什么区别,但是我发现了用例的区别(使用通过apache在python 3.4上通过wsgi运行的django 1.9.1)。在我的应用程序中,ImageFields数据库中有一些图像。如果我在模板中使用如下代码:

<a href="object-{{object.id}}"><img src="{% static object.image %}" height="200px"></a>
Run Code Online (Sandbox Code Playgroud)

然后,如果我使用{% load static %}django则抛出一个TypeErrorCannot mix str and non-str arguments)。据推测,这是因为object.image不是字符串,而是一个ImageField,稍后会转换为字符串。但是,如果{% load staticfiles %}不使用,则不会发生此类错误。

不幸的是,在花费数小时尝试调试问题后,我发现了这种差异。我设法找到了使用第一个选项时的解决方法,即向这样的对象添加字符串转换器方法:

#image string
def image_str(self):
    return str(self.image)
Run Code Online (Sandbox Code Playgroud)

希望这些知识对某人有用。


Uri*_*Uri 5

Django 文档更喜欢现在{% load static %}

{% load staticfiles %}有效,但我认为它已被弃用。

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#static


S.A*_*Ali 1

请参阅文档,其中有一个很好的解释。\n实际上模板标记知道STATICFILE_STORAGE{% static %}的位置

\n\n

正如文档所说:

\n\n
\n
 {% load static from staticfiles %} <img src="{% static "images/hi.jpg"\n %}" alt="Hi!" /> The previous example is equal to calling the url method of an instance of STATICFILES_STORAGE with "images/hi.jpg".\n
Run Code Online (Sandbox Code Playgroud)\n\n

当使用非本地存储后端部署文件时,这尤其有用,如从云服务或 CDN 提供静态文件中所述。

\n\n

如果您\xe2\x80\x99d 想要检索静态 URL 而不显示它,则可以\n 使用稍微不同的调用:

\n\n
{% load static from staticfiles %}\n{% static "images/hi.jpg" as myphoto %}\n<img src="{{ myphoto }}" alt="Hi!" />\n
Run Code Online (Sandbox Code Playgroud)\n
\n\n

希望有帮助!

\n

  • 我仍然不知道什么时候应该使用 `{% load static %}`、`{% load staticfiles %}`、`{{STATIC_URL}}`...并且知道我不知道之间有什么区别`{% load static %}` 和 `{% load static from staticfiles %}` (19认同)
  • 简单地从文档中复制一堆行并没有真正的帮助 (3认同)