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!
Popular modern javascript frameworks you could use for your Django application include React, Angular, and VueJS. There are also lighter javascript frameworks like Alpine.
As django is a backend framework, hence to use the power of python to use that data dynamically requests need to be generated. These requests can be type GET, POST, AJAX etc. But without making any call to the backend the only way to use that data dynamically is to pass it to JavaScript.
{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With