Meteor #each @index传递给动态模板?

时间:2016-02-11 01:31:51

标签: meteor meteor-blaze

我试图将项目的索引从{{#each}}循环传递到动态模板中,但是如何在那里(以干净的方式)将其丢失。

当前代码:

{{#each item}}
{{Template.dynamic template=type data=this}}
{{/each}}

使用此功能,动态加载的模板中无法访问{{@index}}

我也尝试过使用模板助手,但它并没有出现在上下文中跟踪索引。

{{#each item}}
{{Template.dynamic template=type data=itemData}}
{{/each}}

Template.items.helpers({
  itemData() {
    // can't access index in here
    return this;
  }
});

有人可以就如何实现这一目标提出建议吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

使用以下模式解决了这个问题:

... Template.Items
{{#each items}}
{{>Template.dynamic itemConfig @index}}
{{/each}}

Template.items.helpers({
  itemConfig(index) {
    const data = this;
    data.index = index;

    return {
      data,
      template: this.type //this.type is where im storing my template name
    };
  },
});

使用@index作为帮助程序参数,然后Blaze将该对象用作动态模板的配置!

:)

编辑:我找到了another solution。做同样的工作,我更喜欢它的样子。

{{>Template.dynamic template=type data=(templateData @index)}}

templateData基本上与之前的助手相同,但只返回带有data道具的index

答案 1 :(得分:0)

{{#each item}}
{{Template.dynamic template=type index=@index}}
{{/each}}

您可以使用' index'在动态模板中访问索引