Reputation: 2148
I'm using Django and sending a variable from views.py to my template. How can I get that variable in my JS file?
return render(request, 'dashboard/dashboard.html', {"value":123})
Now I want to get the value
variable in my JS file. How can I do it? Inside the template,ie HTML file its easy, just do {{value}} and you get it printed, But I wanted to play with this variable a bit and get it into my JS file. Ho do I do it?
Upvotes: 2
Views: 2037
Reputation: 425
An easy way it's printing in a <script>
tag:
<script>
var value = {{ value|escapejs }};
</script>
Edited:
If you need this var in a separated file you need make a view for render the js file.
Upvotes: 3
Reputation: 47172
Use an input field
<input type="hidden" class="hidden" value="{{ value }}" />
then your JavaScript
var val = document.querySelector(".hidden").value;
or you can put it in any html element and query for the value.
Upvotes: 3