[Django]-How to load bootstrapped models of backbone in Django

5đź‘Ť

âś…

When Backbone talks about bootstrapping, they’re talking about this:

http://documentcloud.github.io/backbone/#FAQ-bootstrap

In other words, they’re saying you should write out the contents of your models in your Django HTML template, inside a script tag.

For instance, let’s say your Django context has a variable called “foo_models”, which contains the JSON representation of all of your foo models. You’d want to edit your Django template to do something like:

<script>
var foo_models = new FooCollection({{foo_models}});
</script>

In this way you can guarantee that your data is ready on the page as it gets loaded, and your JS code can use the JS foo_models to access that data.

Now, your confusion seems to be with how to make the foo_models Python/Django variable in the first place. I’d recommend doing this in your View logic, not in the template, as there you can use the full power of Python and its libraries to serialize the JSON. However, if you do want to do it in your view, you can do so with a syntax that’s pretty similar to what you specified; check out the second answer to this SO question:

Django: Parse JSON in my template using Javascript

👤machineghost

Leave a comment