2

This is good enough for a fixed variable we already know.

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}";
</script>

I have one scenario, where I wanted to create the variable dynamically. e.g -

<script type="text/javascript"> 
for (i = 1, bar = bar , textb = ""; i <= bar ; i++) 
   {
    for (j = 1, category = category , textc = ""; j <= category ; j++)
     {
      var a = "{{someDjangoVariable + i + j}}";
      // Do some more stuff here in UI - create input field dynamically
     }
   }
</script>

In my query dict lets say i have this structure (2 * 2 matrix structure) - {'someDjangoVariable11' : 1, 'someDjangoVariable12' : 23, 'someDjangoVariable21': 256, 'someDjangoVariable22': 31}

Please suggest if there is a way to create variables dynamically.

P.S - The columns and rows of matrix may vary as per User Input. It can be 2 *3, 4 * 3, 1 * 5 etc.

3
  • This question seems to betray a fundamental misunderstanding of how templates and JS works, and the difference between server-side and frontend code. Commented Aug 20, 2016 at 19:58
  • @DanielRoseman : I have edited the question, let me know if still not understandable. Thanks!! Commented Aug 20, 2016 at 20:08
  • I understood the question; the misunderstanding I was talking about was yours. Commented Aug 20, 2016 at 20:46

1 Answer 1

1

This approach will not work since the client side variables can not reach back to the server. What I'd suggest is sending back a dictionary of variables from the server.

Server Side:

data = {'foo': '1', 'bar': '2'}
return render('template.html', data)

Client Side:

<script> var data = {{data|json|safe}}; </script>

Then you can access it in javascript with the original dictionaries keys.

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

2 Comments

Alternatively, you can convert the data to a string with json.dumps() on the server side, and then send that data as a string which removes the need for the "json" filter in the template.
Can you please answer this. I was not very clear on this post. stackoverflow.com/questions/39067756/…

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.