如何在django模板中使用加载webpack的图像? [英] How to use images loaded with webpack in django templates?

查看:115
本文介绍了如何在django模板中使用加载webpack的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Webpack 2 ,并使用 url-loader 加载我的所有图像。在使用webpack之前,我使用了静态模板标签:

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" %}" ... />

现在,webpack将所有图像重命名为某些哈希和分机,如下所示:

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

img.png 成为 img- [somehash] .png 。 (我用于缓存无效

问题是如何在django中加载新的图像(带哈希)模板?!

提前感谢

推荐答案

如何在上下文数据中传递正确的路径?在Django视图中,您将上下文数据传递给模板。您可以使用正则表达式来查找具有哈希的文件的名称。让我们说,你的图像在名为 STATIC_ROOT 链接到所有静态文件的位置的目录中。首先,您需要查找文件:

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)

让我们说你想要的文件名是 picture.png ,它被更改了到 picture-asd12edaq.png 然后,使用正则表达式找到正确的文件名,或者在运算符中简单的 $

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:

文件
break

然后在模板中使用简单的< img src ={ %static {{src}}%}... />

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

这篇关于如何在django模板中使用加载webpack的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆