AllTheGoodNamesWereTaken AllTheGoodNamesWereTaken - 1 year ago 88
Javascript Question

Passing JSON in Django Template to Standalone Javascript File

I have the following code in my

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
import json, requests

platformReq = requests.get(platformUrl, headers={'Authorization': 'Token token="1234"'})

platformData = json.loads(platformReq.text)
return render_to_response('find.html',{'platformList':platformData})

In my template file I have this:

<script src="{% static "js/standalone.js" %}" type="text/javascript"></script>
{# this is where it fetches the json and formats it correctly #}
var js_variable = {{platformList | jsonify}};

The JSON outputs properly from that console.log(), but I get the error:

ReferenceError: function_in_standalone_js is not defined

In my standalone Javascript:

var function_in_standalone_js = function(js_variable)
var options = js_variable['platforms'];

Here's what the output would be, and what the console.log() gives (There are more than 3, but I didn't want to paste the entire thing):

{"platforms": [{"slug": "saturn", "id": 32, "name": "Sega Saturn"}, {"slug": "mac", "id": 14, "name": "Mac"}, {"slug": "vc", "id": 47, "name": "Virtual Console (Nintendo)"}]}

Thanks in advance!

Answer Source

Due to different loading times of the JS in your template you should wrap your inline JS in $(document).ready(function(){...}) to make sure it's run only after the rest of the document has loaded, including external JS files.

      var js_variable = {{platformList | jsonify}};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download