Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using django template variables in a external JavaScript file

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

1 Answers

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);
like image 109
vallentin Avatar answered May 22 '26 13:05

vallentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!