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

后端 未结 1 435
忘了有多久
忘了有多久 2021-01-14 10:58

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

相关标签:
1条回答
  • 2021-01-14 11:29

    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.

    0 讨论(0)
提交回复
热议问题