Meteor template: Pass a parameter into each sub template, and retrieve it in the sub-template helper

你说的曾经没有我的故事 提交于 2019-12-01 08:04:10

When you use {{> child myParam}}, it's calling the child template and associates myParam as current template data context, meaning that in the template you can reference {{paramName}}.

In someOtherHelper you could use this.paramName to retrieve "paramValue". However, when you're using {{#each nodes}}{{> child}}{{/each}}, it means that you pass the content of the current list item (fetched from a LocalCursor or directly an array item) as the template data of child, and you can reference the list item properties using {{field}} in html or this.field in js.

What's happening here is when you call {{> child myParam}}, the myParam helper content OVERWRITES the current node item as template data, that's why it's messing your node list.

A quick (dirty) trick would be to simply extend the myParam helper so that it also contains the template data from the {{#each}} block.

Template.parent.helpers({
  nodes:function(){
    // simulate typical collection cursor fetch result
    return [{_id:"A"},{_id:"B"},{_id:"C"}];
  },
  myParam:function(){
    // here, this equals the current node item
    // so we _.extend our param with it
    return _.extend({paramName:"paramValue"},this);
  }
});

Template.child.helpers({
  someOtherHelper:function(){
    return "_id : "+this._id+" ; paramName : "+this.paramName;
  }
});

<template name="parent">
  {{#each nodes}}
    {{> child myParam}}
  {{/each}}
</template>

<template name="child">
  {{! this is going to output the same stuff}}
  <div>_id : {{_id}} ; paramName : {{paramName}}</div>
  <div>{{someOtherHelper}}</div>
</template>

Depending on what you're precisely trying to achieve, there might be a better approach but this one gets the job done at least.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!