EmberJs: render template inside Handlebars-helper

2019-08-03 04:57发布

问题:

I have this situation in which I have the template-name stored in a variable. I noticed that if you have for example

var config = { view: "PeopleView", .... } ;

that you can't do

{{view App[config.view]}}

If this is possible, I'm still interested in the solution! Anyway, I decided to fix this with a Handlebars helper:

{{setVariableView config}}

...

Ember.Handlebars.registerBoundHelper('setVariableView', function(value, options) {
    return App[value.view].create(value) ; // <-- this doesn't work :)
}) ;

At this point I don't know how to call the compiled PeopleView ? Any suggestions ?

Cheers

回答1:

First you'll want to create your configuration object, as you've done:

App.config = Ember.Object.create({ view: 'App.MyView' });

And then you want to register your helper, which you've done, but it needs to be modified a little bit, since views need to be manually appended when you take this approach:

Ember.Handlebars.registerBoundHelper('setVariableView', function(value, options) {
    var view = eval(value.view).create();
    view.append();
});

And now you can pass in the configuration file to your setVariableView helper, and it will render the view that was passed in to your configuration:

{{setVariableView App.config}}

The only concern is the utilisation of eval. Maybe it's the early morning that's not helping, but I can't think of a better alternative at the moment.