2

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

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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}}")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.