且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Emberjs:如何使用变量中的视图名称渲染视图?

更新时间:2023-11-26 10:45:10

正如您已经提到的,内置的 render 助手仅接受一个字符串以查找要渲染的模板,因此一种可能的解决方案是编写您自己的自定义 render 助手,然后在使用获得正确的名称之后card.get('type')将渲染委托给内置的 render 助手。看起来可能像这样:

As you already mentioned the built-in render helper only accepts a string to lookup the template to render, therefore one possible solution would be to write your own custom render helper, which then after getting the correct name with card.get('type') delegates the rendering to the built-in render helper. This could look something like this:

Ember.Handlebars.registerBoundHelper('renderCard', function(context, card, options) {
  return Ember.Handlebars.helpers.render.call(context, card.get('type'), 'card', options);
});

之后,您可以在模板中像这样使用它:

After that, you could use it like this in your template:

{{#each card in cards}}
  {{renderCard this card}}
{{/each}}



编辑



我还添加了基本的 jsbin ,表明它可以正常工作。

Edit

I've also added a basic jsbin that shows it working.

使用要渲染到模板中的对象数据再次编辑jsbin,请参阅此处

Edited the jsbin again, using object data to be rendered into the template, see here.

可悲的是, DS.FixtureAdapter 不支持嵌入式记录,这是使它工作所需的功能。但是您可以像这样配置原始的 DS.RESTAdapter

Lamentably the DS.FixtureAdapter does not support embedded records which is what you need to make it work. But you could configure you orignal DS.RESTAdapter like this:

App.Adapter = DS.RESTAdapter.extend();

App.Adapter.map('App.Dashboard',
  cards: {embedded: 'always'}
);

App.Store = DS.Store.extend({
  adapter: App.Adapter
});

这样记录就是总是已加载父记录。我想进行此更改将使您在车把助手中对 card.get('type')的调用返回值,而不是 undefined

This way the card records are always loaded with the parent record. I guess doing this change would make the call to card.get('type') in you handlebar helper return the value rather then undefined.

希望有帮助。