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?

3
  • 1
    Include the variable in a div value_value & then just do a get_by_id?! Commented Nov 15, 2013 at 7:12
  • @AshishNitinPatil - Bhai thats a jugaaad (Hope you understands) :D I want something standard. :) Commented Nov 15, 2013 at 7:34
  • Have a look at - stackoverflow.com/questions/298772/… I just wanted to show one of the methods (I knew it to be inefficient) Commented Nov 15, 2013 at 7:36

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

9 Comments

He wants it in his pre-existing scripts which are separately stored from the templates.
He can use this var in any scope, for example: namespace.value = value || null;
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.
@Carlangueitor - Firstly, Its not working, and yes as Ashish said, I want it in a separate JS file.
Its still not working. Says SyntaxError: invalid property id var a = {{ value|escapejs}};
|
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.

2 Comments

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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.