I want to use the template variables in javascript file which is linked to the template.
For eg.
<!-- The template -->
<h1>{{ user.username }}</h1>
<script src="{% static 'profile_page/js/index.js' %}"></script>
// The script file (a different file)
console.log('{{ user.username }}');
Unless your index.js is also being generated by a Jinja template, then having {{ user.username }} inside index.js is going to be cumbersome to resolve.
The easier approach would be to generate a <script> tag, that contains the data your index.js would need. As var username = ...; would be accessible within the subsequent script.
<script>var username = {{ user.username|tojson }};</script>
<script src="{% static 'profile_page/js/index.js' %}"></script>
Now inside your index.js you can simply use the variable as your normally would, i.e.:
console.log(username);
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