How to use images loaded with webpack in django templates?

落花浮王杯 提交于 2019-12-22 01:32:44

问题


I am using Webpack 2 and use url-loader to load all of my images. before using webpack, I used the static template tag like this:

<img src="{% static "img.png" %}" ... />

and now webpack renames all of the images to some hash and ext like this:

img.png becomes img-[somehash].png. (I use this for cache invalidation).

the problem is how to load the new image (with the hash) in django templates ?!

thanks in advance.


回答1:


How about passing correct path in context data? In Django view you are passing context data to the template. You can use regular expressions to find the name of file with hash. Let say that your images are in the directory which variable called STATIC_ROOT links to (place where all static files are). First, you need to find files:

from yourproject.SETTINGS import STATIC_ROOT
all_files = os.listdir(STATIC_ROOT)

Let say that name of the file you want is picture.png, and it was changed to picture-asd12edaq.png Then, find correct file name using regex or simple in operator:

for file in all_files:
    if 'picture' in file and '.png' in file:
        context['src'] = file
        break

Then in template use simple <img src="{% static {{src}} %}" ... />



来源:https://stackoverflow.com/questions/42969399/how-to-use-images-loaded-with-webpack-in-django-templates

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