Home > Net >  How to retrieve Django list as array in Javascript
How to retrieve Django list as array in Javascript

Time:11-13

I'm sending django list from view.py to my javascript. But when I receive the list in javscript, it only return me as string. I tried to print the type of the variable but it show me false which mean its not array list. So how can I retrieve the list as array in Javascript?

View.py

    mergedCompare = [item_listAssigned[f'subject{i}']   ': '   item_listAssigned[f'serial{i}'] for i in range(1, len(item_listAssigned) // 2   1)]
            global context
            context = {
                'mergedCompare': mergedCompare
            }


mergedCompare = ['EMP004: BPCE-RNHC-25G8', 'EMP003: 8FIW-9JRB-NY4J', 'EMP005: 7QF2-6HI9-XKZZ', 'EMP002: SG8P-YQKG-ZV3C', 'EMP001: PBF7-WZHT-WPZR']

JavaScript:

        var assignedDevices = "{{mergedCompare|safe}}"
        const list = assignedDevices;
        console.log(Array.isArray(list)) //false , not array

CodePudding user response:

You can render the JSON content as a JavaScript script with the |json_script template filter [Django-doc]. Then you can load the JSON blobk with JSON.parse(…):

{{ mergedCompare|json_script:"mergedCompare" }}

<script>
var assignedDevices = JSON.parse(document.getElementById('mergedCompare').textContent);
const list = assignedDevices;
console.log(Array.isArray(list))
</script>

CodePudding user response:

Another few approaches in addition to previous answer:

# your view code
...
return render(request, 'some.html', context = {"my_list": ["item1", "item2"]})

# your template code
{{ my_list|safe }}.forEach  // array
  • dump to/from JSON
import json

# your view code
...
mylist = json.dumps(mylistraw)
return render(request, 'some.html', context = {"my_list": mylist})

# your template code
var mylist = JSON.parse("{{mylist}}")
  • Related