django best way to pass data to javascript

风格不统一 提交于 2021-01-27 04:57:29

问题


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?


回答1:


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.



回答2:


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



回答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




回答4:


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


来源:https://stackoverflow.com/questions/38654599/django-best-way-to-pass-data-to-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!