Adding an image tag using static src

944 views
Skip to first unread message

Frederik Lau Rasmussen

unread,
Jul 30, 2021, 5:22:29 PM7/30/21
to oTree help & discussion
Heyo!

I've been trying to add an image using jQuery to a <div>, using the {% static %} way of doing it.

$("myDiv").append(`<img src="{% static "images/card.png" %}"/>`);

When doing it this way, the src of the image becomes the literal string "{% static "images/card.png" %}", and no image is showed on the page.

Is it possible to add the image to the page this way?
If I add the <img> tag directly with the src in the HTML, the image does show up!

I've tried using double quotes, single quotes, literals, saving the path to a variable and so on, however without luck.

Could use a tip on how to make this work, if possible!

Cheers,
Fred

Chris @ oTree

unread,
Jul 30, 2021, 8:46:23 PM7/30/21
to oTree help & discussion
On Friday, July 30, 2021 at 3:22:29 PM UTC-6 fred...@gmail.com wrote:
Heyo!

I've been trying to add an image using jQuery to a <div>, using the {% static %} way of doing it.

$("myDiv").append(`<img src="{% static "images/card.png" %}"/>`);

That should work fine.
This line of javascript is in a template? Can you show the full template code, and then the HTML code that gets generated (use 'view source' in your browser). 

Frederik Lau Rasmussen

unread,
Jul 31, 2021, 8:02:50 AM7/31/21
to oTree help & discussion
Hey Chris,

I managed to get it working! I had seperated my javascript into a seperate file, which stopped it from loading the image on Heroku. By moving my JS back into the template it worked again.

However, I seem to be getting some weird behavior when using the static image paths. I've put a console.log in after getting one of the paths and when running the devserver locally i get what i expect - a path with /static/images/card.png.
But when being hosted on Heroku, it adds a load of characters in the middle of the path, which I can't seem to figure out why.

imagepaths.PNG
The expected outputs should be: 
/static/images/b3.png
/static/images/b4.png
/static/images/r3.png

Any ideas on why, or where the sequence of characters comes from?

Cheers!
Reply all
Reply to author
Forward
0 new messages