【问题标题】:Performance hits from loading Django static tag multiple times多次加载 Django 静态标签会导致性能下降
【发布时间】:2016-12-24 06:57:13
【问题描述】:

除非我做错了,似乎如果您有嵌套模板(即,{% include %} 模板中的模板),您有时需要在嵌套的多个“层”中调用 {% load static %}。例如,假设我有templateA.html:

{% load static %}
<a href={% static "some/path" %}>Some Link</a>
{% include 'templateB.html' %}

然后在`templateB.html中,我有:

{% load static %}
<a href={% static "some/other/path" %}>Some Other Link</a>

据我测试,我必须在两个模板中都包含{% load static %},因为templateB.html 不知道我已经加载了{% static %} 标签。

我的问题是这样的:

假设需要加载{% static %} 标记两次(或更多次,具体取决于嵌套的数量),这种额外加载是否会影响性能?

我不确定当你加载这个标签时 Django 在后台做了什么,但我的直觉是你不想加载和重新加载静态文件。 (因为我们谈论的是一个开源项目,我确实尝试亲自了解一下 templatetag 是如何实现的,但事实证明它有点超出我的理解...... )。

此外,此问题假定有必要始终以这种方式加载标签。如果我缺少某些东西,我会非常有兴趣了解更多信息。谢谢!

【问题讨论】:

    标签: html django django-templates django-staticfiles


    【解决方案1】:

    您必须在每个模板中编写标签。在性能方面,您不必担心,因为它永远不会重新加载或加载静态文件的单独新副本。

    【讨论】:

      【解决方案2】:

      没有开销。 load static 不会“加载和重新加载静态文件”;它只是使 staticfiles 模板标签库中的(已经加载的)代码可用在您的模板中。

      【讨论】:

        【解决方案3】:

        通过使用加载,您可以将来自某个应用的标签和过滤器添加到当前模板的上下文中。它只是为解析器调用parser.add_library() 并更新此特定模板的标签和过滤器列表。你可以检查this method,它是从load tag调用的 如果您不想加载某些内容,可以将其添加到内置函数中。对于 Django 1.9,您可以像这样配置它

        TEMPLATES = [
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': [],
                'APP_DIRS': True,
                'OPTIONS': {
                    'builtins': ['django.templatetags.static'],
                },
            },
        ]
        

        对于旧版本

        from django.template.loader import add_to_builtins
        add_to_builtins('django.templatetags.static')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-12
          • 2023-03-13
          相关资源
          最近更新 更多