2

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?

rainbowFish
  • 265
  • 3
  • 13

1 Answers1

4

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}}
ianpetzer
  • 1,828
  • 1
  • 16
  • 21
  • Thanks for the help, but I can't get this working. I had to change your call to `event.type` to `event.get('type')` and tried changing `'eventable'` to `event.get('eventable')` but that returns an error: `Uncaught TypeError: Object [object Object] has no method 'match' ` in ember-latest.js – rainbowFish May 15 '13 at 17:15
  • Yes.. I edited the answer to use event.get('type') but I believe that that you should leave eventable as is... Assuming it is a proprty on your model... I modified an existing fiddle to show this working: http://jsfiddle.net/ianpetzer/QTdb8/ .... Good luck – ianpetzer May 16 '13 at 10:20
  • Great, it looks like that's working! For some reason when I tried yesterday passing in a string for the second argument, Handlebars was complaining that I could only call `render` once without passing a model. – rainbowFish May 16 '13 at 16:38