I am making a Django website. In it I am trying to access a variable in view.py file in an external static JS file linked to my template.
I tried using the syntax var is_empty = "{{is_empty}}"
, but it didn’t work in a if statement where if(Number(is_empty) == 1)
, and also I tried creating a div in my body(with id = "temp"
) and adding an attribute data-dj = {{is_empty}}
and then using var is_empty = document.getElementById("temp").getAttribute("data-dj");
, but it was showing an error that cannot call getAttribute on null.
Please help!
2
Answers
If is_empty type is boolean then try like this:
You can declare a variable within a script tag in your Django template and then access this variable in your external JavaScript.
In your Django template:
In your external JavaScript file (external.js):
Or you can use data attributes in HTML elements to store Django variables and then access these attributes from your external JavaScript.
In your Django template:
In your external JavaScript file: