Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array in Django to a template and use it with JavaScript

I want to pass an Array to a template and afterwards use it via JavaScript.

In my views.py I have:

arry1 = ['Str',500,20] return render_to_response('test.html', {'array1': arry1}) 

And in my template:

var array1 = {{ array1 }}; 

but when I visit the website it outputs:

var array1 = ['Str',500,20]; 

What do I have to change?

like image 592
Christian Avatar asked Apr 11 '09 12:04

Christian


People also ask

Can you use JavaScript in Django template?

Adding JavaScript to Our Django TemplateWe can add JavaScript to our template using an inline <script> tag or an external JavaScript file. Let's create a app. js file, put it in a js folder that you need to create in the static folder of your application.

How do I run a JavaScript file in Django?

To load JavaScript file, just add the following line of code in index. html file. Run the server by using python manage.py runserver command. After that access the template by localhost:8000/index URL, and it will produce the following output to the browser.

What is a more efficient way to pass variables from template to view in Django?

POST form (your current approach) This answer is perfect and I learned a great deal!


1 Answers

Try using {{ array1|safe }} and see if that makes any difference.

like image 167
Deniz Dogan Avatar answered Sep 20 '22 16:09

Deniz Dogan