Performance hits from loading Django static tag multiple times

泄露秘密 提交于 2020-01-04 06:07:34

问题


Unless I am doing things wrong, it seems like if you have nested templates (i.e., {% include %} a template within a template), you will sometimes need to call {% load static %} in multiple "layers" of the nest. For example, say I have templateA.html:

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

And then in `templateB.html, I have:

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

As far as I can tell from testing, I must include {% load static %} in both templates, because templateB.html does not know that I have already loaded the {% static %} tag.

My question is this:

Assuming that it is necessary to load the {% static %} tag twice (or more times depending on the amount of nesting), is there going to be a performance hit from this extra loading?

I am not sure what Django does under the hood when you load this tag, but my intuition is that you don't want to be loading and reloading static files. (Since we are talking about an open source project, I did actually try to look under the hood myself at how this templatetag is implemented, but it proved to be a little beyond my comprehension...).

Also, this question assumes that it is necessary to always load the tag this way. If there is something I am missing, I would be very interested to learn more. Thank you!


回答1:


There is no overhead. load static does not "load and reload static files"; it just makes available the (already-loaded) code in the staticfiles templatetags library for use in your template.




回答2:


You have to write the tag in every template. In case of performance, you need not to worry as it never reloads or loads a separate new copy of static files.




回答3:


By using load you adding tags and filters from some app into the context for the current template. It just calls parser.add_library() for parser and updates the list of tags and filters for this particular template. You can check this method, and it gets called from load tag If you don't want to load something you can add it in the builtins. For Django 1.9 you can configure it like this

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

and for older versions

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


来源:https://stackoverflow.com/questions/38999652/performance-hits-from-loading-django-static-tag-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!