简体   繁体   中英

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, ie 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?

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM