0

Curious one - how do you set a javascript variable’s name to that of a Django variable?

I need something like:

var “{{django_variable}}” =

I’ve tried this but the script just sees var “” =

Any pointers?

9
  • Have you verified that you are providing a property named "django_variable" in context when you render this template? Commented Jan 28, 2018 at 22:34
  • @Alan Yes, the variable I’ve referenced if used anywhere else renders correctly. Commented Jan 28, 2018 at 22:37
  • I don't think you can do that per se, but you can do what you want to do by creating an object and dynamically setting a property name instead of a standalone variable Commented Jan 28, 2018 at 22:38
  • @MichaelRoberts it works elsewhere in the same template, but not in this location? That is odd. Commented Jan 28, 2018 at 22:39
  • Incidentally, putting quotes around the variable name is invalid syntax. Commented Jan 28, 2018 at 22:40

1 Answer 1

1

I can't imagine why you want to do this, but just remove the quotes.

var {{django_variable}} =
Sign up to request clarification or add additional context in comments.

4 Comments

I’m creating unique variables inside a for loop - those unique variables each specify a unique event listener in the script.
(That is to say, if I generated non-unique event listeners inside the loop both event listeners would do the same thing)
An object - the js equivalent of a dict - is probably a more appropriate way to do this.
Sure, that was also raised in the comments. I think that sounds like the way forward - I could probably even look to do this server side if that’s the case. Return the dict in context?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.