Problem Render backbone collection using Mustache template
I am quite new to backbone js and Mustache. I am trying to load the backbone collection (Object array) on page load from rails json object to save the extra call . I am having troubles rendering the backbone collection using mustache template.
My model & collection are
var Item =  Backbone.Model.extend({
});
App.Collections.Items= Backbone.Collection.extend({
    model: Item,
    url: '/items'
});
and view
App.Views.Index = Backbone.View.extend({
    el : '#itemList',
    initialize: function() {
        this.render();
    },
    render: function() {
        $(this.el).html(Mustache.to_html(JST.item_template(),this.collection ));
        //var test = {name:"test",price:100};
        //$(this.el).html(Mustache.to_html(JST.item_template(),test ));
    }
});
In the above view render, i can able to render th开发者_如何学编程e single model (commented test obeject), but not the collections. I am totally struck here, i have tried with both underscore templating & mustache but no luck.
And this is the Template
<li>
<div>
  <div style="float: left; width: 70px">
    <a href="#">
      <img class="thumbnail" src="http://placehold.it/60x60" alt="">
    </a>
  </div>
  <div style="float: right; width: 292px">
    <h4> {{name}} <span class="price">Rs {{price}}</span></h4>
  </div>
  </div>
</li>
and my object array kind of looks like this

Finally it turns out that mustache doesn't handle array of objects sent to the template, so i had to wrap it with other object like this
render: function() {
    var item_wrapper = {
          items : this.collection
    }
    $(this.el).html(Mustache.to_html(JST.item_template(),item_wrapper ));
}
and in template just looped the items array to render the html
{{#items}}
<li>
<div>
  <div style="float: left; width: 70px">
    <a href="#">
      <img class="thumbnail" src="http://placehold.it/60x60" alt="">
    </a>
  </div>
  <div style="float: right; width: 292px">
    <h4> {{name}} <span class="price">Rs {{price}}</span></h4>
  </div>
  </div>
</li>
{{/items}}
Hope it helps to someone.
Mustache can handle arrays using {{#.}}{{.}}{{/.}}
This happens because mustache expects a key/value pair -being the value an array- for Non-Empty Lists. From the mustache man page, section "Non-Empty Lists":
Template:
{{#repo}}
  <b>{{name}}</b>
{{/repo}}
Hash:
{
  "repo": [
    { "name": "resque" },
    { "name": "hub" },
    { "name": "rip" },
  ]
}
Output:
<b>resque</b>
<b>hub</b>
<b>rip</b>
If you pass only an array, mustache does not have a way to know where to expand it inside the template.
Using Hogan.js implementation.
Given template:
<ul>
{{#produce}}
    <li>{{.}}</li>
{{/produce}}
</ul>
And context:
var context = { produce: [ 'Apple', 'Banana', 'Orange' ] );
We get:
<ul>
    <li>Apple</li>
    <li>Banana</li>
    <li>Orange</li>
</ul>
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论