1

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 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.