5
votes

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);       
});
1
Assuming the output is correct, your code should work; jsfiddle.net/yhtxknk1. I can only assume the {{message.mac[0][0]}} is not giving you the array in a JS-acceptable format. Have you checked what the format of the source looks like when it reaches the client? - Rory McCrossan

1 Answers

10
votes

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.