django best way to pass data to javascript

13,703

Solution 1

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))
        }) 

Solution 2

I had the same problem and this is how I solved it

In the views.py file

context = {'data': json.dumps (data)}
return render (request, 'demo / home.html', context)

Blockquote

In your html

var data = JSON.parse ("{{data | escapejs}}");

Solution 3

That's how I do it too, but I don't pass too much data, only a few parameters that I need to initalize the JS code. The main data is passed though an API.

You can pass a json if you want but you could at least clean the data before rendering it in the template using escapejs

var data = '{{data|escapejs}}';

Hope this helps

Solution 4

There are ways to neatly isolate preloaded serialized data from the rest of your code.

Example 1—assigning preloaded data to a global variable on window, and later using it in your table component:

<html>
<meta charset="utf-8">
<body>
    <script>
        // Loading the data for use in JS components here
        (function () {
            window.tableData = JSON.parse('{{ table_data }}');
        }());
    </script>

    <script src="table.js"></script>
    <!-- table.js uses window.tableData when building the table -->
</body>

Example 2—encapsulate table component as a module, initialize it from the main template and pass the preloaded data.

<html>
<meta charset="utf-8">
<body>
    <table id="theTable"></table>

    <script src="table.js"></script>
    <!-- table.js exports itself globally as window.table -->

    <script>
        // Loading the data and initializing table component
        (function () {
            var tableEl = $('#theTable');
            var tableData = JSON.parse('{{ table_data }}');

            window.table.init(tableData, tableEl);
        }());
    </script>
</body>

And so on!

Want to completely avoid intermixing Django template language and JavaScript?

  • Pass all of your data over XHR—make AJAX requests to the server after your page loads; write a Django view that returns your needed data as JSON which is easy to parse in JavaScript.

Want everything—keep Django template language out and avoid extra XHRs to fetch the data?

  • Look into building your app on a framework such as React.js or AngularJS and utilizing server-side rendering of components.
Share:
13,703

Related videos on Youtube

user3599803
Author by

user3599803

Updated on June 06, 2022

Comments

  • user3599803
    user3599803 almost 2 years

    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?

  • user3599803
    user3599803 almost 8 years
    Actually I am exploring the last method you've suggested. server side rendering of components - what is it, how does it works with django? any reference would be great.
  • Anton Strogonoff
    Anton Strogonoff almost 8 years
    @user3599803 sure, last time I stumbled across github.com/markfinger/python-react, README has quite a bit about Django-specific integration. Not using it myself yet, was just researching around.
  • Muhammed Bilal
    Muhammed Bilal almost 4 years
    Dear i want to put this data on template using javascript how can i do that can u help .
  • Psionman
    Psionman almost 3 years
    Simple and works perfectly, but beware generic names for variables like "data". Took me an hour to sort out a conflict as "data" had been used (without thinking) elsewhere in my application and this really screwed it up