views:

4424

answers:

4

Hello,

When i render a page using the Django template renderer, i can pass in a dictionary variable containing various values so i can manipulate them in the page using {{ myVar }}.

Is there a way to access the same variable in Javascript (perhaps using the DOM, i don't know how Django makes the variables accessible), i want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.

Many thanks,

Alistair.

+19  A: 

The {{variable}} is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just text.

Having said that, you can put this kind of substitution into your javascript

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

gives you "dynamic" javascript.

S.Lott
Note though that according to [this solution](http://stackoverflow.com/questions/298772/django-template-variables-and-javascript/1187881#1187881), this is vulnerable to injection attacks
Casebash
+2  A: 

For a dictionary, you're best of encoding to JSON first. You can use simplejson.dumps() or if you want to convert from a data model in App Engine, you could use encode() from the GQLEncoder library.

jamtoday
+7  A: 

The suggested solution of:

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

Is vulnerable to JS injection if someDjangoVariable contains client entered data, even if encoded to JSON. If it contains the string

'</script>...'

the browser will parse that as a closing tag for the script.

O Peng
A: 

How javascript returns variable back to views.py?

Thiti