I have a django application storing static images on digital ocean spaces. I can easily display these static images in my template by doing:<img>{% static 'images/my_image.png' %}</img>
If I inspect the HTML page after this loads, I will see something like:
https://nyc3.digitaloceanspaces.com/nameofmyspace/nameofmyspace-space-static_DEV/images/my_image.png?AWSAccessKeyId=XXXXXXXXXXXXXX&Signature=XXXXXXXXXXXXXXXXXX%3D&Expires=1621600823
But now I want to have this image change dynamically using javascript.
So I tried:
document.getElementById(id+"dynamicImage").src = "{% static 'images/my_image_2.png' %}";
Which almost works, but the image does not load. And the reason for this is after inspecting the src
that the javascript supplied:
https://nyc3.digitaloceanspaces.com/nameofmyspace/nameofmyspace-space-static_DEV/images/my_image.png?AWSAccessKeyId=XXXXXXXXXXXXXX&Signature=XXXXXXXXXXXXXXXXXX%3D&Expires=1621600823
You can see wherever there was an &
it appended amp;
to it.
What is the correct way to do this?
I can think of 2 ways to correct this, but they seem hacky.
- I could hard code the URL’s into the javascript, which will be an updating nightmare as things change
- I could do
<img id = 'my_image' hidden >{% static 'images/my_image.png' %}</img>
for all the links I plan on using, then access this URL in the javascript usinglet URL = document.getElementById("my_image").innerHTML;
. This will be less of an updating nightmare, but seems hacky and must be a better way.
Advertisement
Answer
I solved it by doing:
document.getElementById(id+"dynamicImage").src = ("{% static 'images/my_image_2.png' %}").replace(/&/g, "&");
.replace(/&/g, "&")
will replace all &
with &
.
The/
and /g
is regex to replace all.