0

I have sent a variable in context from my django python code as so:

context = {
    "data": data,
}
return render(request, "template.html", context)

but do not know how to access it in my javascript file. I have tried accessing it like this:

data_from_django = {{ data }}

However this simply gives me a syntax error. Please can someone tell me the correct way to access this variable.

M. Alex
  • 673
  • 5
  • 26
  • Have you tried ```data_from_django = {{ data|safe }}```? – cagrias Aug 01 '19 at 11:58
  • Possible duplicate of [Django Template Variables and Javascript](https://stackoverflow.com/questions/298772/django-template-variables-and-javascript) – bdoubleu Aug 01 '19 at 12:02
  • use this: data_from_django = "{{ data|safe }}". If you don't use quotes, javascript will consider it as variable. – sandeep Aug 01 '19 at 12:13

1 Answers1

1

IN Javascript you have to use the variables within the quotes.

data_from_django = '{{ data }}'

if "data" is a JSON value, be sure to use {{ data | safe }}

In the case where variable and javascript code is not in the same html file,the above method will fail.

In the case of separate js file, wrap the variable with a id and later refer to it in the js file:

//template.html

<div id="data_from_django">{{ data }}</div> 

//sample.js

var data_from_django = 
document.getElementById("data_from_django").innerHTML; 
Milan
  • 434
  • 1
  • 4
  • 9