0

I have an 'int Array' e.g. format [0,3,5,4,6], I have passed this through context. Now in my HTML page I have my JavaScript/JQuery... I thought it'd be as simple doing {% for i in array %} i {% endfor %} but this doesn't seem to be working for me to access the values from a loop. Can you pass a context to JavaScript from Django? how can I get around this problem?

edit the passing shouldn't be a problem if I access an index of the array by creating a variable in my view and passing that -> this will output fine in the script by simply doing {{contextgivenname}}

edit2: if i do {{arrayname}} it will return the first value. But only the first value. So the only way to return all is to loop through it; which isn't working.

anArray2 = [int(i['age']) for i in anArray]
{
'anArray2':anArray2
}

In JavaScript/Jquery when I'm trying to grab the data and use it {{anArray2}} = first value in it.. but if I loop via as mentioned above then nothing.

6
  • post your code, as you should be able to pass a list to the context and do the for loop as indicated. another option is to use json.dumps(array_var) into the context, then do {{ array_var_context|safe }} Commented Mar 18, 2016 at 0:10
  • done - May I add that I'm trying to add the data into a chart thing but that shouldn't matter cause when I just do {{array}} in it, the first value will be put into the chart.. but no values will be if I try loop through them Commented Mar 18, 2016 at 0:22
  • not sure what you are trying to do in your anArray2 assignment, but so long as its a proper array, in the template {% for i in anArray2 %}i{% endfor%} should work, although won't be proper javascript array. better to use json.dumps in your view context. Commented Mar 18, 2016 at 0:29
  • convert the previous array to an int array and only grabbing one thing rather than the other crap the other array was returning from the db Commented Mar 18, 2016 at 0:38
  • are you sure that its returning a multi value array? Commented Mar 18, 2016 at 0:40

1 Answer 1

0

best way to get javascript usable variables would be to do this in your view.

array_var = [1, 2, 44, 323]

return render(request, 'template.html', { 'arrayList': json.dumps(array_var) })

then in the template.

<script>
  var arrayList = {{arrayList|safe}};
  //... you js script
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

would you access the values via a javascript forloop or django forloop on the 'arrayList' ?
its now in your template in javascript, so you would pass this array to your chart program, or do whatever you want with it in javascript.

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.