0

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!

1

2 Answers 2

2

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:

<script type="text/javascript">
    var myVar = "{{ django_variable }}";
</script>
<script src="path/to/your/external.js"></script>

In your external JavaScript file (external.js):

console.log(myVar); // Access the Django variable

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:

<div id="myElement" data-myvar="{{ django_variable }}"></div>
<script src="path/to/your/external.js"></script>

In your external JavaScript file:

var myVar = document.getElementById('myElement').getAttribute('data-myvar');
console.log(myVar);
Sign up to request clarification or add additional context in comments.

1 Comment

This ought to be obvious, but do take care when a script is passed through the Django template not to code {{ for anything except Django substitutions. Code { { where the two braces are JavaScript block delimiters. The whitespace is significant and the errors if you get this wrong are gnarly. Ditto } }
0

If is_empty type is boolean then try like this:

if ("{{is_empty}}" === "true")

Comments

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.