gongarek
gongarek

Reputation: 1034

List in template tag used in javascript file

As title say I want to use list from views.py to javascript file. I read this topic, but in my case it doesn't work: link

My views.py:

...
arr = ['first', 'second', 'third']
return render(request, "something.html",{"array": arr})
...

something.html:

...
<script>
     array_js = eval("{{ array|escapejs }}");
</script>
<script src="{% whatever.js %}"></script>
...

I am using array_js in whatever.js file. It's works fine, but I am using eval function. I don't want to use it, but I don't know how to make it work without eval function.

I am beginner, so please be patient. Thank You

Upvotes: 0

Views: 45

Answers (1)

victorfsf
victorfsf

Reputation: 51

Since arrays are considered valid JSON, you can just use JSON.parse:

array_js = JSON.parse('{{ array|escapejs }}')

But be sure to set it as an JSON on the view:

import json

...

return render(request, "something.html", {"array": json.dumps(arr)})

Upvotes: 1

Related Questions