问题
Is there any way to pass a variable context to the {{render}} helper?
For instance, I have a polymorphic relationship on my model, and I want to render the appropriate view for each different type (without have to write a whole string of if statements.
my events template looks like this:
<ul>
{{#each event in model}}
<li>
{{event.time}} {{render event.type event.eventable}}
</li>
{{/each}}
</ul>
the event.type is a string and is set to song. If I use {{render 'song' event.eventable}} everything works great. But passing the variable string 'song' produces nothing.
Can this be done?
回答1:
You can achieve this by writing your own Handlebars Helper which determines the template to render and then delegates to the build in render helper. Try this:
Ember.Handlebars.registerBoundHelper('renderEvent', function(callingContext, event, options) {
return Ember.Handlebars.helpers.render.call(callingContext, event.get('type'), 'eventable', options);
});
Then in your template you would call the template as follows:
{{#each event in model}}
{{renderEvent this event}}
((/each}}
来源:https://stackoverflow.com/questions/16556631/calling-handlebars-render-with-a-variable-name