Rendering to JS with Jinja produces invalid number rather than string

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.

Leave a Comment