Is it possible to switch the template partially based on the hash value in Mustache?

Ok, so I'm trying to grab Mustache.js for rendering views in javascript. I have an API that returns several β€œevents” that can be of different types. I want events to be done in (very) different ways, depending on their type:

data : { events: [ {title: 'hello', type: 'message'}, {title: 'world', type: 'image'} ] } 

Ideally, I could do something like this:

 {{#events}} {{#message}} <div class="message">{{title}}</div> {{/message}} {{#image}} <span>{{title}}</span> {{/image}} {{/events}} 

But that (really?) Would make me reorganize my data into:

 data : { events: [ {message: {title: 'hello'}}, {image: {title: 'world'}} ] } 

Is there a better way to solve this without refactoring my data? Or am I just going to bite a bullet?

+4
source share
1 answer

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).

+2
source

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


All Articles