Emberjs:如何使用变量中的视图名称渲染视图? [英] Emberjs: How to render a view with the view name in variable?

查看:88
本文介绍了Emberjs:如何使用变量中的视图名称渲染视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在板上添加一些卡,所有卡都非常不同。所以我想为每个可以绑定不同事件和模板的卡创建不同的视图。我在纸牌模型中设置了一个类型属性来区分纸牌。

i would like to add some cards to a board, all cards are very different. so i want to create different view for each card that can bind different events and template. I set a 'type' property in the card model which to distinguish the cards.

板模板如下所示:

{{#each card in cards}}
  {{render card.type card class="card"}}
{{/each}}

但是,渲染帮助的第一个参数不能是变量,只能是卡查看名称字符串。

However, the first argument for the render help can not be a variable, it can only be the card view name string.

有人知道如何实现吗?

anyone know how to achieve this?

推荐答案

正如您已经提到的,内置的 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.

希望有帮助。

这篇关于Emberjs:如何使用变量中的视图名称渲染视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆