Why is {% load static %} a dependency for {% get_media_prefix %}?

。_饼干妹妹 提交于 2019-12-11 17:47:36

问题


I've been using {% get_media_prefix %} for a very long time. I was explaining this to someone when he pointed this out.

Why do I need to declare {% load static %} in order to use it?

It even uses in the documentation's example code here.

To an extent I understand that static files and media files are similar in nature. Even when we use them with combination of nginx+gunicorn, nginx handles both of them(we let everything else proxy, but not these).

But still we have a separate MEDIA_URL and STATIC_URL as well as MEDIA_ROOT and STATIC_ROOT defined for these files.

Then why {% load static %} needs to be declared in order to use {% get_media_prefix %} ?

Thanks in advance.


回答1:


In order to use a template tag in your HTML you must first load the module that contains it.

So, accorrding to the source code of get_media_prefix template tag, this template tag lives inside django/templatetags/static.py.

That's why you have to load it every time you use it, in every HTML template.

This, of course, applies to every template tag usage. At the top of every HTML file you load the template tags and then you use them. Just like you import a function in your python code.

UPDATE: From the Django 1.3 release notes:

In previous versions of Django, it was common to place static assets in MEDIA_ROOT along with user-uploaded files, and serve them both at MEDIA_URL. Part of the purpose of introducing the staticfiles app is to make it easier to keep static files separate from user-uploaded files. Static assets should now go in static/ subdirectories of your apps or in other static assets directories listed in STATICFILES_DIRS, and will be served at STATIC_URL.

As you can see, Django used to treat both static and media the same. Since Django 1.3 this changed, but the template tag not. No big deal. It's just a convention.



来源:https://stackoverflow.com/questions/45656855/why-is-load-static-a-dependency-for-get-media-prefix

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