Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django best way to pass data to javascript

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?

like image 947
user3599803 Avatar asked Jul 29 '16 08:07

user3599803


4 Answers

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

like image 82
pleasedontbelong Avatar answered Sep 20 '22 00:09

pleasedontbelong


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}}");
like image 35
Domtry Avatar answered Sep 23 '22 00:09

Domtry


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))
        }) 
like image 41
Igor Avatar answered Sep 20 '22 00:09

Igor


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.
like image 37
Anton Strogonoff Avatar answered Sep 24 '22 00:09

Anton Strogonoff