I am trying to create an image tag for a Jinja template with a variable from Ajax.
success: function (response) {
var pythonResponse = "<ul id='userList'>";
$.each(response,function(index,value) {
console.log(`path is ${value[0]}`)
pythonResponse += `<li onClick = 'selectUser("${value[1]}")'> ${value[1]}`
pythonResponse += `<img src={{ url_for('static', filename='${value[0])}')}}/></li>`
console.log(pythonResponse);
});
The line in question is this one
pythonResponse += `<img src={{ url_for('static', filename='${value[0])}')}}/></li>`
When I run this code the variable value[0] which contains the file path, is rendered out as a bunch of gobbledygook. This is what it looks like %24%7Bvalue%5B0%5D%29%7D/ but it should look like this /myfolder/myFile.jpg. I have confirmed that the variable does indeed equal what it is suposed to equal and if i hard code the file path into the filename='' then it works.
Why is this variable turned from this /myfolder/myFile.jpg into this %24%7Bvalue%5B0%5D%29%7D/?
The order of application here is somewhat confusing. If I'm understanding correctly that the javascript is being applied first, then the answer below should help.
Jinja is escaping your variable for safety. It's possible to introduce security problems in your applications by using a variable the way you are using it here. For information lookup XSS (cross site scripting) attacks for more information.
If you're sure the variable is safe, then Jinja allows you to avoid this encoding with the safe filter.
pythonResponse += `<img src={{ url_for('static', filename='${value[0])}') | safe}}/></li>`