I want to pass a string to some JavaScript in a template. However, the string is being interpreted as an (invalid) number when the JavaScript runs. How do I pass a string to a JavaScript variable?
@app.route('/loadNext')
def loadNext():
return render_template('next.html', value='1.1.1.1')
$("#loadtable").ready(
function(){
var tmp = {{ value }};
alert(tmp);
});
The problem is that
{{ '1.1.1.1' }}
renders as
1.1.1.1
Quotes are not included. JavaScript tries to parse this as a number and can't. Fortunately, Flask includes a Jinja filter for this.
var tmp = {{ value|tojson }};
tojson
will include quotes around strings and omit them for numeric values. The filtered value, when rendered by Jinja, is valid JavaScript with the correct type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With