python-coder
python-coder

Reputation: 2148

how to get a python variable in JS Django

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

Answers (2)

Carlangueitor
Carlangueitor

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

Henrik Andersson
Henrik Andersson

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

Related Questions