Load Django “static” template tag library globally without explicitly loading it in every file

大城市里の小女人 提交于 2019-12-10 21:27:59

问题


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

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