[Fixed]-How to use Django variable in JavaScript file?

22👍

You need to print it before your script tag

<html>
<head>
<script>
    var username = {{user.get_username}};
</script>
<script src="/static/youtube.js"></script>
...

Then you can use the username variable inside your youtube.js as it is declared as a javascript global variable.

👤cor

9👍

With the newer versions of Django they implemented a way of doing this with. This way you’ll also be protected from XSS

https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#json-script

To your Django variable add |json_script:'id_of_the_script_tag'

{{ cart_total|json_script:'cart_total' }}

This will create an HTML <script> tag with the id=cart_total

In the javascript file parse the JSON and save it in your variable

const cart_total = JSON.parse(document.getElementById('cart_total').textContent);

3👍

The above solution is Almost Right just need to change the Django variable to String then it will work for sure.

<html>
<head>
<script>
    var username = "{{user.get_username}}";
</script>
<script src="/static/youtube.js"></script>

Leave a comment