AllTheGoodNamesWereTaken AllTheGoodNamesWereTaken - 4 months ago 8
Javascript Question

Passing JSON in Django Template to Standalone Javascript File

I have the following code in my views.py:

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>
<script>
{# this is where it fetches the json and formats it correctly #}
var js_variable = {{platformList | jsonify}};
console.log(js_variable);
function_in_standalone_js(js_variable);
</script>


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'];
console.log(options)
}


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

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.

<script>
    $(document).ready(function(){
      var js_variable = {{platformList | jsonify}};
      console.log(js_variable);
      function_in_standalone_js(js_variable);
    });
</script>
Comments