[Fixed]-Is there a way to index a Django/Jinja list with a javascript variable?

1👍

There are many way to do.

1. First way is manually define variable at jinja2 rendering time.

If python code is:

def sample(request):
    return render(request, 
                  'sample_template.html',
                  {
                      'data': [1, 2, 3, 4, 5],
                  })

and sample_template.html is:

<html>
    <head><title>sample</title></head>
    <body>
        <script>
        var data = "{{ data }}";
        // and now, you can parse value of data variable. And then using it.
        </script>
    </body>
</html>

2. Define another endpoint for getting data (Create API)

python:

from django.http import JsonResponse

def sample(request):
    return render(request, 'sample_template.html')

def api(request):
    return JsonResponse({'data': [1, 2, 3, 4, 5]})

html:

<html>
    <head>
        <title>sample</title>
        <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    </head>
    <body>
        <script>
        var data;
        $.ajax({
          url: 'endpoint-for-api'
        }).done(function(d) {
            data = d;
        });
        // and also you using it.
        </script>
    </body>
</html>

Leave a comment