2

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?

python-coder
  • 2,128
  • 5
  • 26
  • 37

2 Answers2

3

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.

Carlangueitor
  • 425
  • 2
  • 15
  • He wants it in his pre-existing scripts which are separately stored from the templates. – shad0w_wa1k3r Nov 15 '13 at 07:12
  • He can use this var in any scope, for example: `namespace.value = value || null;` – Carlangueitor Nov 15 '13 at 07:17
  • 2
    No, no. Never couple JavaScript with Django template language. Makes the code really tightly coupled plus this way clutters the global namespace (window), which is something you really don't want. – Henrik Andersson Nov 15 '13 at 07:17
  • @Carlangueitor - Firstly, Its not working, and yes as Ashish said, I want it in a separate JS file. – python-coder Nov 15 '13 at 07:23
  • Its still not working. Says `SyntaxError: invalid property id var a = {{ value|escapejs}};` – python-coder Nov 15 '13 at 07:28
  • @limelights - I agree with you, but here in my code, I want to do the calculations at the client side. Had I been doing at the server -side, I would have easily passed the variable to the template. There's no specific reason for calculating at the client-side. Whats your say. Open for discussion. Thanks – python-coder Nov 15 '13 at 07:30
  • @Carlangueitor - No No. I cannot do that. isnt there any alternative? – python-coder Nov 15 '13 at 07:32
  • I can´t Downvote. You can try with {{ value }} (with no filter). But I think that @limelights answer is better. – Carlangueitor Nov 15 '13 at 07:38
  • Sure, and you can do that, just pass the "start value" to the hidden field and continue to do your calculations in javascript. – Henrik Andersson Nov 15 '13 at 08:00
3

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.

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
  • a useful approach is to stick it on a `data-` attribute. usually when you want to do this the value is related to a particular DOM element anyway. – Eevee Nov 15 '13 at 07:28
  • Apart from when using the `data-` attribute and you update it via jQuery (for example) then the original value is cached by jQuery so that's a bummer. – Henrik Andersson Nov 15 '13 at 08:00