Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly pass django list/dictionary to javascript

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  "
like image 407
Abdukahhor Kurbonov Avatar asked Sep 02 '25 14:09

Abdukahhor Kurbonov


1 Answers

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);
like image 166
Nico Griffioen Avatar answered Sep 05 '25 07:09

Nico Griffioen