django best way to pass data to javascript [duplicate]
Asked Answered
T

5

10

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?

Truth answered 29/7, 2016 at 8:56 Comment(1)
{{data}} - it's json data? #38621316Automation
C
7

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}}");
Canzona answered 6/7, 2020 at 2:35 Comment(2)
Dear i want to put this data on template using javascript how can i do that can u help .Ceremonial
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 upEbullience
L
5

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

Lubricator answered 29/7, 2016 at 9:17 Comment(0)
A
5

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))
        }) 
Automation answered 29/7, 2016 at 10:49 Comment(0)
O
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.
Obliquity answered 29/7, 2016 at 9:28 Comment(2)
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.Truth
@Truth 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.Obliquity
D
2

You can use json_script filter.

Safely outputs a Python object as JSON, wrapped in a tag, ready for use with JavaScript.

https://docs.djangoproject.com/en/4.2/ref/templates/builtins/#json-script

Diannediannne answered 14/1 at 23:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.