【问题标题】:Image source from django variable来自 django 变量的图像源
【发布时间】:2018-11-16 11:06:46
【问题描述】:

我正在我的 html 代码中寻找一种不同的可能图像源,具体取决于 python 函数的结果。

例如:

state = isOnline()

是一个可以判断设备是否在线的函数,它会返回:

是的

那么我会得到

IMG_URL = imgSource(state)

将返回在线图片的来源

静态'项目\img\true.jpg'

然后我会通过我的views.py用作:

def device(request):

    return render(request, 'device.html', {'IMG_URL': IMG_URL})

然后我可以在我的 html 代码中使用这个变量。

<img src="{% IMG_URL %}" alt="Post">

希望大家能帮帮我,谢谢!

【问题讨论】:

    标签: python html django image variables


    【解决方案1】:

    你可以使用类似的东西:

    def device(request):
        # this could be generated in any number of ways, but this is a simple one
        IMG_URL = 'http://example.com/online_image.jpg' if is_online() else '/local/img/offline_image.jpg'
    
        return render(request, 'device.html', {'IMG_URL': IMG_URL})
    

    有一些想法可以检查您是否在线here

    【讨论】:

    • 我的问题更多是关于如何将图像源作为变量传递,因为使用 {{ IMG_URL }} 它总是成为一个字符串?如果我没有两种可能性,这种类型的解决方案可能非常困难,可能没有?
    • 没有。图像源始终是一个字符串,这就是我要传递给渲染函数的内容。我建议你弄清楚那个来源是尽可能接近调用render(),就像在我的更新中一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    相关资源
    最近更新 更多