How to load bootstrapped models of backbone in Django

廉价感情. 提交于 2019-12-14 03:51:41

问题


when backbone app was loaded(for my app it means the page loaded),I need the initial collection data, and backbone docs says:

<script>
  var accounts = new Backbone.Collection;
  accounts.reset(<%= @accounts.to_json %>);
  var projects = new Backbone.Collection;
  projects.reset(<%= @projects.to_json(:collaborators => true) %>);
</script>

I don't understand this. Dose it mean I should render the page with the initial data like

{{collection_initial_data}}

I am using django on backends, so how do I translate the above code into django template, something like

 <script>
  var accounts = new Backbone.Collection;
  accounts.reset({{ @accounts.to_json }});
  var projects = new Backbone.Collection;
  projects.reset({{ @projects.to_json(:collaborators => true) }});
</script>

anyway I am really confused about getting the initial data of backbone collection.


回答1:


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



来源:https://stackoverflow.com/questions/16195361/how-to-load-bootstrapped-models-of-backbone-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!