0

I have this flask app

@app.route('', methods=['POST'])
def my_function():
 (...some functions...)
 map = some_url    
 return render_template ("main.html", map = map)

And I want to insert "map" into my JavaScript (.js is in /static):

 btn.addEventListener("click", function(){
   var newMap = document.createElement("IMG");     
   newMap.setAttribute("src", "{{map}}");
   newMap.setAttribute("width", "300");
   newMap.setAttribute("height", "300");

I do a print(map) before return render_template and it prints well but newMap is created but empty, like with no src.

Toto Briac
  • 908
  • 9
  • 29
  • Maybe take a look at this question, which assumes you are using jinja for template rendering: https://stackoverflow.com/questions/11178426/how-can-i-pass-data-from-flask-to-javascript-in-a-template – Jon Mar 12 '20 at 13:19
  • @Jon, I already went through this post but when I use a `{{ variable }}` it raises a SyntaxError in my JavaScript console. – Toto Briac Mar 12 '20 at 13:33
  • Check this out. If the javascript is in /static it is not a template, and jinja won't render it: https://stackoverflow.com/questions/29335633/import-javascript-files-with-jinja-from-static-folder – Jon Mar 12 '20 at 14:10

1 Answers1

0

There is an alternate solution which will work fine. You can create a hidden input and set its value to the map variable

<input type="hidden" value={{map}} id="inputId"/>

Now using javascript access the value and change setAtrribute second parmaeter to mapValue

mapValue = document.getElementById("inputId").value
newMap.setAttribute("src", mapValue);


                                
charchit
  • 1,492
  • 2
  • 6
  • 17