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.

3
  • Have you tried data_from_django = {{ data|safe }}? Commented Aug 1, 2019 at 11:58
  • Possible duplicate of Django Template Variables and Javascript Commented Aug 1, 2019 at 12:02
  • use this: data_from_django = "{{ data|safe }}". If you don't use quotes, javascript will consider it as variable. Commented Aug 1, 2019 at 12:13

1 Answer 1

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; 
Sign up to request clarification or add additional context in comments.

2 Comments

Do I have to do anything in template.html?
Just to note that wrapping the variable in a div will work but I think it has security issues

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.