Mustache.js / Hogan.js with Backbone.js

I am trying to implement some code using backbone.js
and hogan.js (http://twitter.github.com/hogan.js/)

Hogan.js was developed against a mustache test suite,
so everything that is true for templates, as indicated here, also holds true for hogan.js.

My problem is passing Backbone.Collection to Hogan / Mustache.

For a simple template:

{{name}} 

Hogan / Mustache, expecting something like this, works great:

 {"name":"How Bizarre","artist":"OMC"} 

However my Backbone.Collection:

a)
[{"name": "Like Bizarre", "artist": "OMC"}]

Or that:

b) [{"name": "How Strange", "artist": "OMC"}, {"name": "Sexual Healing", "artist": "Marvin Gaye"}]

From the demo page http://mustache.github.com/#demo I can not iterate through any of a) or b) Backbone.Collection obejcts.

Can anyone point out how I can do this?

 var Song = Backbone.Model.extend({ defaults: { name: "Not specified", artist: "Not specified" } }); var Album = Backbone.Collection.extend({ model: Song }); var song1 = new Song({ name: "How Bizarre", artist: "OMC" }); var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" }); var myAlbum = new Album; myAlbum.add(song1); myAlbum.add(song2); 

I'm going through trying to do it by passing my Backbone.Colleciton object like this: myAlbum.toJSON ()

 var template = "{{name}}!"; var template = Hogan.compile(template); this.el.html(template.render(myAlbum.toJSON())); 

Thanks.

+4
source share
3 answers

It looks like you are passing the Hogan collection, not a standalone model.

Try this instead:

 _.each(myAlbum,function(album) { this.el.append(template.render(album.toJSON())); }); 
+1
source

I ran into the same predicament using the Hogan template in the Backbone collection.

 var o = {}, c = Album.toJSON(); o.data = c; this.$el.html(template.render(o)); 

and in my template, I refer to {{#data}} {{/ data}} to iterate over the collection.

+1
source

I tried the spine rendering call

 Backbone.Marionette.Renderer.render = (template, data) -> HoganTemplates[template].render data 

Works well with puppet. however problems with backbone.forms.

0
source

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


All Articles