url_for Is Not Understanding My Variables

Issue

Here, I’m trying to make it so that, whenever a user uploads an image, it will be displayed to all users. "Data" contains the file name i.e. "files/dog.png". For some reason, newImg.src only becomes "/static/". My code is shown below:

var chatDiv = document.getElementById('messages');
const newImg = document.createElement("img");
newImg.src = "{{url_for('static', filename = data )}}"
chatDiv.appendChild(newImg)

I have already tried to use Jinja2 string interpolation like this:

newImg.src = "{{url_for('static', filename = {{ data }} )}}"

However, this results in the following error:

jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}'

And yes, even after removing the brackets, my code still doesn’t work(pls reopen this post).

Assistance would be much appreciated!

Solution

Ok, I was able to find a work around! You have to use .replace to replace the string with another variable.

newImg.src = "{{url_for('static', filename = 'data')}}".replace('data', data)

Answered By – 77 ChickenNug

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published