简体   繁体   English

将flask变量从javascript传递到html

[英]Pass a flask variable from javascript to html

I try to programmatically generate a html div in JavaScript and add it into my html page when a button is clicked. 我尝试以编程方式在JavaScript中生成html div,然后在单击按钮时将其添加到我的html页面中。 Everything works pretty well except that my variables coming from Flask are not displayed. 除了不显示我来自Flask的变量之外,其他所有东西都运行良好。

Example : 范例:

Javascript : Javascript:

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

Python : 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". 在html中单击该按钮时,它显示: {{my_string}}而不是“ Variableàafficher”。

Is there a way to displays the variable correctly ? 有没有办法正确显示变量?

Hope this helps. 希望这可以帮助。

var my_str = '{{ my_string }}';
var html_to_add = "<div><p>" + my_str + "</p></div>";

Please try this: 请尝试以下方法:

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

Pay attention to the punctuation mark `, it is backquote. 注意标点符号`,它是反引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM