问题
I want to use the static tag in templates like so:
<img src="{% static "img/test.jpg" %}">
I've found that that requires me to put
{% load static %}
at the beginning of every template file. Since I'm using it everywhere, I would like it to be a globally available tag so I don't need to put {% load static %} to use it.
In my settings I do have:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.static',
)
I saw both of these questions: Make django static tag globally available and Load a Django template tag library for all views by default though neither seems to answer the question. In the former the question wasn't clear and in the later I get errors when I try to use:
from django.template.loader import add_to_builtins
add_to_builtins('django.core.context_processors.static')
Perhaps I'm not putting it in the correct location, or perhaps it's already part of the core so doesn't work?
How can I automatically get the static tag added into all template files without explicitly loading it for every file?
回答1:
I think a lot of answers forget where you need to put the code. Well, let me start by telling you that you can use the following code to get the job done:
from django.template.loader import add_to_builtins
add_to_builtins('django.templatetags.static')
Now put this, in your main urls.py
file. This worked for me.
回答2:
Replace django.core.context_processors.static
with django.templatetags.static
:
>>> from django.template import Context,Template
>>> from django.template.loader import add_to_builtins
>>> add_to_builtins('django.templatetags.static')
>>> Template('{% static "img/test.jpg" %}').render(Context())
'/static/img/test.jpg'
BTW, your code has a typo: Replace add_to_bultins
with add_to_builtins
.
来源:https://stackoverflow.com/questions/18709803/load-django-static-template-tag-library-globally-without-explicitly-loading-it