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

ghz 1years ago ⋅ 632 views

Question

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.


Answer

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.