0

I try to programmatically generate a html div in JavaScript and add it into my html page when a button is clicked. Everything works pretty well except that my variables coming from Flask are not displayed.

Example :

Javascript :

function add_div(){
    var html_to_add = "<div><p>{{my_string}}</p></div>";
    $(html_to_add).insertBefore("#submit-btn");
}

Python :

@app.route("/")
def main_page():
    return render_template("index.html",my_string="Variable à afficher")

When the button is clicked in html, it displays : {{my_string}} instead of "Variable à afficher".

Is there a way to displays the variable correctly ?

4
  • Can you try this var html_to_add = str("<div><p>" +{{my_string}}+"</p></div>"); Commented Oct 1, 2018 at 16:47
  • It doesn't work unfortunately, even if I put the javascript code into a <script> tag. Here is the screenshot : i.sstatic.net/h91t8.png Commented Oct 1, 2018 at 17:00
  • Did you put the value of my_string directly? Commented Oct 1, 2018 at 17:11
  • Try these lines var my_str = '{{ my_string }}'; and var html_to_add = "<div><p>" + my_str + "</p></div>"; Commented Oct 1, 2018 at 17:17

2 Answers 2

2

Hope this helps.

var my_str = '{{ my_string }}';
var html_to_add = "<div><p>" + my_str + "</p></div>";
Sign up to request clarification or add additional context in comments.

1 Comment

It works perfectly, even with Jinga expression! Thanks a lot @Arihant
0

Please try this:

var html_to_add = `<div><p>${my_string}</p></div>`;

Pay attention to the punctuation mark `, it is backquote.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.