Reputation: 23
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.
Upvotes: 2
Views: 1438
Reputation: 44
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.
Upvotes: 1