简体   繁体   English

为什么要为每个模板加载静态文件,即使它已被扩展?

[英]Why load staticfiles for every template even if it is extended?

I have a base.html file which has some 'random' html code and I have the following code: 我有一个base.html文件,其中包含一些“随机”HTML代码,我有以下代码:

{% load staticfiles %}
<!DOCTYPE html>
<html>
   <head>
      ... 
     {% block extra_js_top %}{% endblock %}
   </head>
   ...
</html>

In my index.html file I extend base.html and I load some extra javascript files: 在我的index.html文件中,我扩展了base.html并加载了一些额外的javascript文件:

{% extends "base.html" %}
...
{% block extra_js_top %}
   <script type="text/javascript" src="{% static "js/somejs.js" %}"></script>
{% endblock %}

The problem is that extra javascript doesn't load because of the static var. 问题是因为静态var而无法加载额外的javascript。 It doesn't load even if I extend base.html which have the {% load staticfiles %} inside the template. 即使我在模板中扩展了具有{% load staticfiles %} base.html ,它也不会加载。 Finally I solved the problem adding one more {% load staticfiles %} at index.html . 最后,我解决了在index.html中再添加一个{% load staticfiles %}的问题。

My question is why we should add {% load staticfiles %} for every template we use even if we extend a file that has it already? 我的问题是为什么我们应该为我们使用的每个模板添加{% load staticfiles %} ,即使我们已经扩展了已经存在的文件?

As per Django's latest documentation , this is done for the sake of maintainability and sanity 根据Django的最新文档 ,这是为了可维护性和理智性

When you load a custom tag or filter library, the tags/filters are only made available to the current template – not any parent or child templates along the template-inheritance path. 加载自定义标记或过滤器库时,标记/过滤器仅可用于当前模板 - 而不是模板继承路径中的任何父模板或子模板。

For example, if a template foo.html has {% load humanize %}, a child template (eg, one that has {% extends "foo.html" %}) will not have access to the humanize template tags and filters. 例如,如果模板foo.html具有{%load humanize%},则子模板(例如,具有{%extends“foo.html”%}的模板)将无法访问人性化模板标签和过滤器。 The child template is responsible for its own {% load humanize %}. 子模板负责自己的{%load humanize%}。

This is a feature for the sake of maintainability and sanity. 这是为了可维护性和理智性的特征。

Because that's the way template tags work. 因为这是模板标签的工作方式。 You need to load each library for every template file that uses them. 您需要为每个使用它们的模板文件加载每个库。

It's logical that you'll need {% load staticfiles %} wherever you want url expansion to occur. 在您希望网址扩展发生的任何地方,您都需要{% load staticfiles %} ,这是合乎逻辑的。 If you have that happening in both base.html & index.html , you'll have to include it at both places (as you've already figured). 如果您在base.htmlindex.html都有这种情况,那么您必须在两个地方都包含它(正如您已经想到的那样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM