0

I am looking for a way different possible image source in my html code, depending on result of a python function.

Exemple if:

state = isOnline()

is a function that can say if a device is online or not, it returns:

True

then I would obtain

IMG_URL = imgSource(state)

would return the source for online image

static 'project\img\true.jpg'

which I would then through my views.py used as:

def device(request):

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

and then I could use this variable in my html code.

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

I hope you guys will be capable to help me, thanks !

1 Answers1

0

You can use something like:

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})

There are some ideas for checking if you're online or not here.

Jamie Bull
  • 12,889
  • 15
  • 77
  • 116
  • My question is more about how to pass an image source as a variable since with {{ IMG_URL }} it always get to be a string ? And in case that I don't have only 2 possibilities a solution of this type could be very difficult probably no ? – David G Jun 06 '18 at 18:06
  • No. An image source is always a string, and that's what I'd pass to the render function. I'd suggest you figure out what that source is as close to calling `render()` as possible like in my update. – Jamie Bull Jun 06 '18 at 18:50