20

I know that we can use Django variable in templates(html files) with {{variable}}, but how can I use a variable Django in a Javascript file that included in the template?

For example here is my template.html:

<html>
<head>
<script src="/static/youtube.js"></script>
...

how can I use variable {{user.get_username}} in youtube.js? not in template.html cause I did't wrote my script here...and when I use {{user.get_username}} in Javascript file youtube.js it caused an error "invalid token { ", but in the template it works fine.

Thanks a lot!

3 Answers 3

23

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.

Sign up to request clarification or add additional context in comments.

11 Comments

in fact later I got un error, for example my username is Tom, there is what in the console window: Uncaught ReferenceError: Tom is not defined
This is because you are using Tom as the variable name, when "Tom" is the content of the variable username
No I was logged as the name "Tom", I used var username = {{user.get_username}} in the script but I got the error
If you get an error saying that Tom is not defined, is because you are trying to use it as a variable. Please, show me what you are trying and I will try to help you, but this is not related with your original question.
I defined a variable global username in the template as you proposed and my tag have an attribute owner name...it seems that I should use var username = "{{user.get_username}}" cause owner name is string, thank you very much my problem solved:)
|
10

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);

Comments

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>

1 Comment

This is the correct one if the value is string

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.