The mustache has no logic, so you have nothing to do with the clean template code except switching to Handlebars .
A utility convenient for Mustache is to declare an assistant and use it to select which template to display. This is a bit confusing, but you can avoid going from Mustache if this is something you cannot change:
var base_template = '{{#events}}' + '{{{event_renderer}}}' + '{{/events}}'; var message_template = '<div>message: {{title}}</div>'; var image_template = '<div>image: {{title}}</div>'; var data = { events: [ {title: 'hello', type: 'message'}, {title: 'world', type: 'image'} ], event_renderer: function() { return Mustache.render('{{> ' + this.type + '}}', this, {message: message_template, image: image_template}); } } Mustache.render(base_template, data);
The trick here is that you create a basic template that will be an iterator, and pass event_renderer as an assistant. This helper, in turn, will call Mustache.render again, using partial events to visualize each type of event that you may have (which is {{partial}}).
The only ugly part here is that you need to add this event_renderer member to your JSON data, but apart from that everything should be fine (in Handlebars you can declare it as an helper, and there is no need to combine this with your data).
source share