0

Let's say I have a list of books I want to render in a certain way with JavaScript, as opposed to just doing something like the following;

{% for book in books %}
  <div class="book-container">
    <div class="title">{{ book.title }}</div>
    <div class="author">{{ book.author }}</div>
  </div>
{% endfor %}

I want to load the json representation of books into a JavaScript variable (perhaps a list of Book objects I've defined in my client side code) and render it in a more "fancy" way using JavaScript.

Anyways, I was thinking of sending a post request on page load to get the data and loading it into a variable. Is there a better way to do this? These are my initial naive guesses.

EDIT: In essence, I want to learn of a legitimate/recommended way to get a context server side and load it into a JavaScript variable client-side on page load.

zallarak
  • 5,287
  • 7
  • 38
  • 54

2 Answers2

2

Why not just output it as JSON directly in the template? That'll save the extra POST request.

<script type="text/javascript">
    var books = {{ my_json_data }}
</script>

Now books is a global JS variable that can be accessed from your other scripts.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • could that be the explanation for this implementation, just the fact that the API resided in the project's scope? http://stackoverflow.com/questions/11583039/django-project-with-a-server-side-apimixin – Hedde van der Heide Aug 03 '12 at 21:34
1

Have a look at django-tastypie which provides a REST framework. You might also want to look into backbone.js and general AJAX

https://github.com/toastdriven/django-tastypie

http://backbonejs.org/

Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100