How does one access Django template variables in JavaScript?
-
I am using Django/jQuery to render my web pages for my project. I have a particular predicament that I have not been able to resolve. I hope that some one may be able to help. <b>Set up:</b> I use jQuery on ready function to invoke Google's chart api to generate pie and bar charts. http://code.google.com/apis/chart/image/docs/gallery/pie_charts.html and http://code.google.com/apis/chart/interactive/docs/gallery/barchart.html My django template is essentially this: <pre> <script type="text/javascript"> function drawBarChart() { var getNewDataObject = function() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Name'); data.addColumn('number', 'Amount'); return data; }; var allPersons = new Array() var persons = new Array(); {% for person in persons %} var personArray = new Array(); personArray[0] = '{{person.name}}'; personArray[1] = {{ person.amount }}; allPersons[forloop.counter0] = personArray; {% endfor %} var personDataObject = getNewDataObject(); personsDataObject.addRows(allPersons.length); for (i=0;i<allPersons.length;i++) { for (j=0;j<allPersons[i].length;j++) { personDataObject.setValue(i, j, allPersons[i][j]); } } var chart = new google.visualization.ColumnChart($('div#personChart').get(0)); chart.draw( personDataObject, {title: 'Person Amount.', width:300, height:250, vAxis: {title: 'Amount'}, hAxis: {title: 'Name'}, allowHtml: true}); } </script> </pre> Issue This code only works if this code is in html file inside a script tag but not if I were to put this in a separate javascript file. The javascript file can neither recognize django template variables nor can it parse them. I would like to have all my javascript code in a separate Javascript file that I can import in other html file if I want to generate a bar chart in another file. I tried the following approach <pre> <script type="text/javascript"> drawBarChart($('div#personChart').get(0), {{ persons }}); </script> .... <script type = "text/javascript" src = "http://www.foo.com/scripts/charts.js" /> </body> </pre> The issue is that Django seems to be passing the repr implementation of list of Person objects. I would like to be able to access the actual list of Person objects. I don't know how to make it work. Other links on Quora and StackOverflow (http://stackoverflow.com/search?q=access+django+template+values+in+javascript) do not provide the correct answer. FYI... I tried to implement the first solution from SO search result but it does not work for me. I would be grateful for any help that anyone can give. I
-
Answer:
Declare a js variable in a script tag within HTML and directly use in external js files.<script>var context_var= "{{variable}}";</script>You may use context_var in any of your external js files.For details you may refer to http://www.mutaku.com/wp/index.php/2012/03/accessing-django-template-variables-in-javascript/
Gagan Khanijau at Quora Visit the source
Other answers
I donât like to print my variables directly inside a script tag. I prefer to create a JSON with all variables Iâll need, and then print this JSON in a data-* attribute on the body tag.Something like this: <body data-js-vars=â{{ js_vars }}â> <script> var my_vars = JSON.parse(document.getElementsByTagName('body')[0].getAttribute('data-js-vars') || '{}'); </script> </body>
Eduardo Matos
If you put your Javascript in a separate file then you need to render the data that it is going to work with into the web-page before you read in the script. If you donât there is, as you rightly point out, no way for the Javascript to access the data.I would suggest that you dump the data you need as JSON into a <script> tag above the tag you are using to include the Javascript file and then you should find it works. Or you can use a data attribute as per Eduardoâs answer above, and then access it via the DOM - whichever you prefer.Good luck,Oliver
C. Oliver Godby
Related Q & A:
- How to connect to a Pervasive Database using javascript?Best solution by Stack Overflow
- How Can I add Latitude, Longitude dynamically in Javascript?Best solution by Stack Overflow
- How to create a underscore template dynamically?Best solution by Stack Overflow
- How to load `static` tag by default in Django template?Best solution by tangowithdjango.com
- How do you download a template for Blogger?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.