3

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!

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.