Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Django variable in JavaScript file?

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!

like image 757
Yuqing Wei Avatar asked Apr 18 '16 08:04

Yuqing Wei


People also ask

Can you use Django with JavaScript?

Popular modern javascript frameworks you could use for your Django application include React, Angular, and VueJS. There are also lighter javascript frameworks like Alpine.

How send data from Python to JavaScript in Django?

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.

Why is {% include %} used?

{% 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.


1 Answers

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.

like image 194
cor Avatar answered Sep 23 '22 10:09

cor