问题
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