Lucas Ou-Yang
Lucas Ou-Yang

Reputation: 5655

Iterating Django template variables in javascript, access by a changing index

How would it be possible to access or iterate a django list within javascript using a changing INDEX.

For example:

<script>
    for (var i=0; i < "{{ django_list|length }}".toInt(); i++) {
         var e = "{{ django_list" + i.toString() + " }}"; // this gives an error
         ...    //  it does not parse a chunked ^ template variable properly
         ...
    }
</script>

Some background. This is a pure .js file that is being rendered by django. That part works, it just does not interpret a substringed out django template var syntax.

I'd prefer a solution which avoids encoding into JSON or anything similar. Template form is preferred because I need the methods of the variables.

Thanks.

Upvotes: 1

Views: 1120

Answers (2)

Sohaib
Sohaib

Reputation: 4694

Can't you use a for each loop?

{%  for item in django_list  %}
//Whatever you wish to do with item goes here
{% endfor %}

For more see the link https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for-empty

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798746

As always, encode as JSON.

{% load jsonify %}

var data = {{ django_list|jsonify }};

for (...) {
   ...
}

Upvotes: 1

Related Questions