简体   繁体   中英

EmberJS registerHelper to dynamically render a template in Ember 1.8

I'd like to dynamically render a template, like this:

{{#each layout in layouts}}
   {{render layout.get('type') layout}}
{{/each}} 

The problem is that render doesn't expect a variable as its first arguments, so in the older EmberJS-versions, a workaround was possible by registering a helper:

Ember.Handlebars.registerBoundHelper('render_layout', 
  function(callingContext, layout, options) {
    return Ember.Handlebars.helpers.render.call(callingContext, 
                layout.get('type'), 'layout', options);
});

and in the template:

{{#each layout in layouts}}
     {{render_layout this layout}}
{{/each}} 

Unfortunately the thing doesn't work in newer ember versions. Ember.Handlebars.helpers.render.call expects 3 arguments but I can not get them right. Any ideas? I've tried: (this, layout.get('type'), options)

and in the template:

{{#each layout in layouts}}
     {{render_layout layout}}
{{/each}} 

I get Uncaught TypeError: Cannot read property 'pushChildView' of null

... and many others.

Any suggestions would be greatly appreciated.

Components allow you to specify layoutName . And you can dynamically compute the layout name based on a parameter passed into the component.

App.XRenderComponent = Ember.Component.extend({
  tagName: "",
  layoutName: function(){
    return this.get('displayLayout.type'); 
  }.property('displayLayout'),
});

Then you can just do

  <script type="text/x-handlebars" id="index">
    {{#each layout in model}}
      {{ x-render displayLayout=layout }}
    {{/each}}   
  </script>

See working example here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM