I am running into this “old problem”: Jinja variable parsing only works on the html template (passed in to render_template), so if your Javascript code is in a static JS file the Flask/Jinja variables can't be accessed”. Jinja Flask issue: Uncaught SyntaxError: Unexpected token { in JSON at position 1 at JSON.parse Does anyone know if there is already a solution for this. It's ugly to embed the JS code in the HTML file
1 Answer
You can use the tojson Jinja filter to safely embed only the JSON data into the document, then load it in JS.
{% set data = [1, 2, 3, 4] %}
<script id="data" type="application/json">{{ data|tojson }}</script>
And in the external JS file:
const value = JSON.parse(document.getElementById('data').textContent);