为什么即使扩展了模板也要为每个模板加载静态文件? [英] Why load staticfiles for every template even if it is extended?

查看:57
本文介绍了为什么即使扩展了模板也要为每个模板加载静态文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 base.html 文件,其中包含一些'random'html 代码,并且我具有以下代码:

I have a base.html file which has some 'random' html code and I have the following code:

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

在我的 index.html 文件中,我扩展了 base.html ,然后加载一些额外的javascript 文件:

In my index.html file I extend base.html and I load some extra javascript files:

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

问题是由于以下原因,无法加载额外的JavaScript:静态变量即使我扩展了 base.html (在模板中包含 {%load staticfiles%} ),它也不会加载。最后,我解决了在 index.html 处再添加一个 {%load staticfiles%} 的问题。

The problem is that extra javascript doesn't load because of the static var. It doesn't load even if I extend base.html which have the {% load staticfiles %} inside the template. Finally I solved the problem adding one more {% load staticfiles %} at 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?

推荐答案

按照Django最新的文档,这样做是出于维护和理智的考虑

As per Django's latest documentation, this is done for the sake of maintainability and sanity


当加载自定义标签或过滤器库时,标签/过滤器仅可用于当前模板
,而不会包含任何父或子
模板

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.

例如,如果模板foo.html具有{%load humanize%},则为子级
模板(例如,具有{%extended foo.html%})的用户无法使用
访问人性化模板标签和过滤器。子模板
负责自己的{%load humanize%}。

For example, if a template foo.html has {% load humanize %}, a child template (e.g., one that has {% extends "foo.html" %}) will not have access to the humanize template tags and filters. The child template is responsible for its own {% load humanize %}.

此功能是为了保持可维护性和合理性。

This is a feature for the sake of maintainability and sanity.

这篇关于为什么即使扩展了模板也要为每个模板加载静态文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆