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

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

I am trying to figure out how to pass a parameter into a sub-template that is in an each block and use the parameter in the sub-template as well as sub-template helper. Here is what I tried so far:

template:

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

js:

Template.parent.nodes = function() {  //return a list }; Template.parent.myParam = function() { return {"paramName" : "paramValue"}; }; Template.child.someOtherHelper = function() { //How do I get access to the "paramName" parameter? }

So far, it hasn't been working, and it seems somehow mess up my input node list also.
Thanks for help.

回答1:

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.



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