Teo
Teo

Reputation: 41

Passing array from Django view to HTML/JS

I'm sending an array from a django view to an html (in which there is a JS script) but the array seems to be a string. In fact if I try to console.log(array[0]) or console.log(array[1]) it returns in the first case [ and in the second case '

The code is:

Django view

def results(request):
   h = request.POST['h']   
   name = request.POST['name']

   array = [h, name]
return render(request, 'app/index.html', {'h':h, 'array':array})

index.html

<script>
   var h = "{{ h }}"   //this is 3 
   var array = "{{ array|safe }}"  //this is ['3', 'John']
   console.log(h)
   console.log(array[0])
   console.log(array[1])

The console is:

3 

[

'

I wish it was:

3

3

John

Do you have any idea how can I access the n value of the array? Thanks

Upvotes: 1

Views: 544

Answers (2)

Ajay Kumar
Ajay Kumar

Reputation: 1655

Try the package django-jsonify

pip install django-jsonify

Then add jsonify to django INSTALLED_APPS

In your template

{% load jsonify %}

var array = {{ array|jsonify }}

Hope this helps you, if any thing please let me know.

Upvotes: 0

kamilyrb
kamilyrb

Reputation: 2627

You can use {{ array|safe }} instead of "{{ array|safe }}" withouth any extensions.

Upvotes: 1

Related Questions