I have a list of items and want to pass it to javascript array. Django version 2.2.3
In my views.py:
my_list = ["one", "two"]
context = {
'my_list ': json.dumps(my_list),
}
return render(request, 'my_template.html', context)
my_template.html
<script>
var my_array = JSON.parse("{{ my_list|safe }}")
document.write(my_array )
</script>
According to the answers in most topics, my code is valid, but it doesn't display any data.
Also tried:
<script>
var my_string = "{{my_list}}";
var my_array = my_string.split(',');
document.write(my_array)
</script>
In this case when i want to display it i get
[" one "
As of Django 2.1, you can now use the json_script template tag to include a python object as JSON in your template.
In your case, that would look like this:
{{ my_list |json_script:"my_array" }}
You can then access it from your script with:
var myArray = JSON.parse(document.getElementById('my_array').textContent);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With