Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering to JS with Jinja produces invalid number rather than string

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);       
});
like image 216
sklearning Avatar asked Oct 26 '15 11:10

sklearning


1 Answers

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.

like image 61
dirn Avatar answered Oct 04 '22 02:10

dirn