Search code examples
javascriptpythonvariablesflaskapostrophe

Error displaying a variable from Flask into javascript code


This is my FLASK variable {{ list_fruits }} when I display it between the <body> brakets in the browser I get :

<body>
{{ list_fruits }}
</body>

[ ['Bananas', 8], ['Kiwi', 3], ['Mixed nuts', 1],['Oranges', 6], ['Apples', 8] ]

But when I display it between the javascript <script> brackets the Apostrophes converts to &#39; so I get something like this:

<script>
{{ list_fruits }}
</script>


[ [&#39;Bananas&#39;;, 8], [&#39;Kiwi&#39;, 3], [&#39;Mixed nuts&#39;, 1],[&#39;Oranges&#39;, 6], [&#39;Apples&#39;, 8] ]

How to prevent javascript from transferring the Apostrophes to &#39;?


Solution

  • Try {{ list_fruits|tojson|safe }} to inject JSON data into your template.