How to use django variable in javascript file?

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

For example, here is my template.html:

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

how can i use the variable {{user.get_username}} in youtube.js ? not in template.html because I didn’t write my script here ... and when I use {{user.get_username}} in the youtube.js javascript file, it caused the error "invalid token {", but in the template it works fine .

Thank you so much!

+4
source share
1 answer

script

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

username youtube.js, ​​ javascript.

+7

All Articles