Reputation: 539
I'm having a for loop where i need to assign a python value to a javascript variable and i can't really make it work:(
{% for row in temp %}
var year = {{ row[0]|safe }}
{% endfor %}
I've tried in many ways but it will always give me
Uncaught SyntaxError: Unexpected token var
What's the right syntax for this?
Upvotes: 0
Views: 95
Reputation: 6766
The new line before the closing of the for loop is not inserted into the document, so the code running on the client side (e.g. for a loop of length 2) is this:
var year = '2018'var year = '2019'
If you try running this code, the exception you mentioned is raised. So this is a client-side error. The simplest solution is to add a semicolon at the end of the row, which allows multiple javacript declarations on the same row:
{% for row in temp %}
var year = {{ row[0]|safe }};
{% endfor %}
Resulting in (for my example):
var year = '2018';var year = '2019'
I must say though, I do not understand the logic behind your code, as the variable 'year' gets overwritten upon each iteration.
Upvotes: 1