【问题标题】:How to use images loaded with webpack in django templates?如何在 django 模板中使用通过 webpack 加载的图像?
【发布时间】:2017-03-23 07:10:24
【问题描述】:

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

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

现在 webpack 将所有图像重命名为一些 hash 和 ext,如下所示:

img.png 变成 img-[somehash].png。 (我用它来使缓存失效)。

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

提前致谢。

【问题讨论】:

    标签: django webpack django-templates


    【解决方案1】:

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

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

    假设你想要的文件名是picture.png,然后改成picture-asd12edaq.png 然后,使用正则表达式或简单的in 运算符找到正确的文件名:

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

    然后在模板中使用简单的&lt;img src="{% static {{src}} %}" ... /&gt;

    【讨论】:

    • 我不确定你指的是什么路径?!
    猜你喜欢
    • 2018-02-13
    • 2015-12-21
    • 2021-06-27
    • 1970-01-01
    • 2017-03-23
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    相关资源
    最近更新 更多