django best way to pass data to javascript

user3599803 picture user3599803 · Jul 29, 2016 · Viewed 11.5k times · Source

I used to "tie" my data to the DOM until I've discovered the data binding libraries. My question, say I have a table which contains model records, how can I build that table with JS, i.e pass the objects into javascript rather then straight build the table in template?

so far from searching the only way I've found is things like this:

var data = '{{data}}';  

{{data}} could be json for this example.

which seems ugly and bad to me, to put template code in javascript, and also I don't like the idea of global variables in javascript (old way and it does not scale well). It also won't allow me to put that in external JS file. Is there's a better (and clean) way?

Answer

Igor picture Igor · Jul 29, 2016

django template autoescape all tags {{ }}.

If table_data already json data in template tag. Simple.

<script>
var myTable = {% autoescape off %}{{ table_data }}{% endautoescape %};
</script>

not need bracket and quote, it's array in javascript (such as var example = ['test'];)

If data not json, return it in request (render template). Example

import json
from django.shortcuts import render

def home(request):
    table_data = MyModel.objects.select_related().values('items1', 'items2')
    return render(
        request, 
        'main.html', 
        {
          'table_data': json.dumps(list(table_data))
        })