jbrown
jbrown

Reputation: 7996

How to dynamically load ember components by name in a template?

My question is basically the same as on this answer, but I can't get the code to work with ember 1.7.0 and & ember-cli.

I have a widget property in my model, and in my template I want to have something like:

{{#each question in questions}}
{{#with question}}
  <label>{{title}}</label>
  {{render-component widget params=params}}
{{/with}}
{{/each}}

And a question model that looks like:

{ id: 6,
  title: "Is this a yes/no situation?",
  help_text: 'Pick an option',
  widget: 'yes-no',
  params:
  {
    yes: {
      text: 'You picked yes',
      class: 'success'
    },
    no: {
      text: 'Be careful, you picked no',
      class: 'danger'
    }
  }
}

I've created a render-component helper that contains the following:

import Ember from 'ember';

function renderComponent(componentPath, options) {
  console.log('inside helper with comp=' + componentPath + ', opts=' + options);
  var component = Ember.Handlebars.get(this, componentPath, options);
  var helper = Ember.Handlebars.resolveHelper(options.data.view.container, component);
  return helper.call(this, options);
}

export {
  renderComponent
};

export default Ember.Handlebars.makeBoundHelper(renderComponent);

But this doesn't work. component is undefined. The API docs for Ember.Handlebars.get aren't very helpful in explaining what the options parameter is. Also, there's no mention of a resolveHelper method in the docs now, so I don't know if the code is out of date anyway.

How can I load components by name from a variable?

Upvotes: 3

Views: 2518

Answers (3)

Ed4
Ed4

Reputation: 2305

This question is quite out of date. Ember includes a built-in dynamic component helper and has for a long time.

Upvotes: 4

Vasiliy vvscode Vanchuk
Vasiliy vvscode Vanchuk

Reputation: 7169

Another one implementation for render-component you can find here

https://github.com/vvs-code/ember-render-helper

It allow pass name and argument/parametrs from dynamical properties

Upvotes: 0

jbrown
jbrown

Reputation: 7996

OK so it should be:

helpers/render-component.js:

import Ember from 'ember';

function renderComponent(componentPath, options) {
  console.log('inside helper with comp=' + componentPath + ', opts=' + options);
  var helper = Ember.Handlebars.resolveHelper(options.data.view.container, componentPath);
  return helper.call(this, options);
}

export {
  renderComponent
};

export default Ember.Handlebars.makeBoundHelper(renderComponent);

Use with:

{{render-component widget params=params}}

Upvotes: 0

Related Questions