Problem Rendering a collection of base stations using a Mustache template

I am new to highways and mustaches. I am trying to load a basic collection (an array of objects) to load a page from a rails json object to save an extra call. I'm having trouble rendering the collection using a mustache template.

My model and collection

var Item = Backbone.Model.extend({ }); App.Collections.Items= Backbone.Collection.extend({ model: Item, url: '/items' }); 

and browse

 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 rendering view, I can display one model (commented out test object), but not collections. I am completely amazed here, I tried both with underlining patterns and with a 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 array of objects looks like this:

enter image description here

+6
source share
4 answers

Finally, it turns out that the mustache does not process an array of objects sent to the template, so I had to wrap it with another object like this

 render: function() { var item_wrapper = { items : this.collection } $(this.el).html(Mustache.to_html(JST.item_template(),item_wrapper )); } 

and the template just looped through an array of elements for rendering 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 this helps someone.

+7
source

Mustache can handle arrays with {{#.}}{{.}}{{/.}}

+7
source

This is because a mustache expects a key / value pair - value for an array - for non-empty lists. From the mustache 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 only pass an array, the mustache has no way of knowing where to expand them inside the template.

+4
source

Using Hogan.js .

This 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> 
+1
source

Source: https://habr.com/ru/post/898150/


All Articles