1

Well, maybe this is a silly question, but i couldn't find the answer so far. So, i am rendering a view in Django (i will do the code generic to make the problem easier), and the python side looks something like this:

...
marray = [1, 2, 3, 4, 5]
...
return render(request, "template.html", {"marray": marray})

Now, in the template.html file, I want to access the array, but the index must be determined by a JavaScript variable:

var index = 2;
var mvar = {{ marray.index }};
console.log(mvar);

Output wanted:

3

Obviously, the previous code does not work, it's just to show what I want. Any suggestions?

Thanks.

  • Possible duplicate of [How to pass an array in Django to a template and use it with JavaScript](https://stackoverflow.com/questions/739942/how-to-pass-an-array-in-django-to-a-template-and-use-it-with-javascript) – internet_user Dec 18 '17 at 13:13
  • I think it's not a duplicate due to the access to the index of the array in a single line. Thanks – Joaquin Miranda Dec 18 '17 at 13:35

1 Answers1

0
var index = 2;
var marray = {{ marray|safe }};
var mvar = marray[index];
// OR: var mvar = {{ marray|safe }}[index];

Note that here index will probably either be constant, or be determined by the context, so there might be better ways to do this.

internet_user
  • 3,149
  • 1
  • 20
  • 29