Django 模板包含不共享静态文件

Django template's include not sharing static files

我有一个大型 Django 项目,其中包含多个模板,这些模板后来被合并以动态构建页面,我面临一个奇怪的问题如下:

  1. 我有一个 base.html,其中包含所有需要的导入,包括 JS 和 CSS。

  2. 我在assets里面有两个CSS/JS的子文件夹,一般都是在base.html的末尾导入。

现在,随着我的项目越来越大,我决定宁愿导入脚本,例如:

<script type="text/javascript" src="{% static "js/base.js" %}"></script>
<script type="text/javascript" src="{% static "js/menus/projects.js" %}"></script>
<script type="text/javascript" src="{% static "js/menus/sensors.js" %}"></script>

包含在每个单独的 HTML 文件中,而不是全部都在 base.html 中,我希望没有问题,因为据我所知 include 语句也应该传输上下文,为了参考,这些是 include 感兴趣的陈述:

{% include "applications/Devices/deviceDashboard.html" %}
{% include "applications/Devices/deviceDashboard/listCard.html" %}
{% include "applications/Devices/deviceDashboard/editCard.html" %}
{% include "applications/Devices/deviceDashboard/graphCard.html" %}

在所有这些中,如果我尝试按原样 运行 它,我会得到以下结果:

TemplateSyntaxError at /

Invalid block tag on line 25: 'static'. Did you forget to register or load this tag?

当我尝试使用与以前相同的脚本导入标签时,当我对每个单独的页面使用 {% load static %} 时,这个问题就消失了。我的 base.html 中有 {% load static %},但它仅适用于该文件,不适用于通过 include 函数调用的任何子文件。

为什么 include 不在此处复制上下文?或者默认情况下它不复制“静态”?我怀疑这应该是我对 include 应该如何在这里工作的一个简单误解,但我在搜索时找不到任何东西。最后,如果它是如何导入的,我该如何解决这个问题?

在django项目中定义静态文件设置settings.py

STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "static/")

MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

也将此添加到您的项目主urls.py

urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Django的load模板标签只加载特定模板文件的包,不通过extendsinclude标签继承。

查看解释 this bug report:

My understanding is that this is a feature, not a bug. The template system only provides the tags loaded in each template file itself so that templates can be reused without having to guess at what their environment expectations are.

A fix for the problem of having to put {% load i18n %} in every template might be to add an app-specific automatically loaded template setting, so each app author can decide what the base namespace for their templates is. This would require adding an app-specific configuration system, and somehow letting the template module know what the 'current app' is.

如果您希望特定标签在所有模板中可用,您可以使用此处使用的方法: