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?

1 Answer 1

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}}
Sign up to request clarification or add additional context in comments.

3 Comments

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
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: jsfiddle.net/ianpetzer/QTdb8 .... Good luck
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.