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.

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great! var mvar = {{ marray|safe }}[index]; is what i was wanted. I don't know how it did not occur to me. Many thanks.

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.