Alex Rivera | Logout

How can I use the variables from "views.py" in JavasScript, "<script></script>" in a Django template?

Asked 2008-11-18T13:52:31.717
321

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

Is there a way to access the same variable in JavaScript, <script></script> (perhaps using the DOM; I don't know how Django makes the variables accessible)? I want to be able to look up details using an Ajax lookup based on the values contained in the variables passed in.

Edit
Report

2 Answers

408

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

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

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

This gives you "dynamic" JavaScript code.

answered 2008-11-18T14:00:58.737
9

For a dictionary, you're best off 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.

answered 2008-11-20T08:19:31.700

Your Answer