0

I am trying to pass a json from django to a template html file with javascript staticfile.

view.py

import json
def view(request,...)
...
    return render(request,'index.htm',"g1":json.dumps({"id":1,"name":2})

index.html

<head>
<script language=javascript" src="/static/myapp/myscript.js"></script>
</head>
<body onload="init();">
<div>I am here</div>
</body>

myscript.js

var json = {{g1}};
function init(){
}

myscript.js is not working. Without {{g1}} statement in .js file, it works. Please help.

cweiske
  • 30,033
  • 14
  • 133
  • 194
Shruti
  • 63
  • 8

1 Answers1

0

I don't believe the variable will be passed into the myscript.js. You have to add the js inline within the template to get it:

<script>
var json = {{g1}};
function init(){
}
</script>

Also according to other stackoverflow answers, this may be vulnerable to injection attacks if you do not use this:

escapejs filter: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#escapejs

safe filter: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#safe

Other sources: Django Template Variables and Javascript

Community
  • 1
  • 1
Hieu Le
  • 738
  • 4
  • 8