2013-08-23 62 views
2

我想弄清楚如何将参数传递到每个模块中的子模板中并使用参数子模板以及子模板助手。以下是我试过到目前为止:
流星模板:将参数传递到每个子模板中,并将其检索到子模板帮助器

模板:

<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? 
} 

到目前为止,一直没有工作,它看起来有点乱了我的输入节点清单也。
感谢您的帮助。

回答

6

当您使用{{> child myParam}}时,它调用子模板并将myParam作为当前模板数据上下文,这意味着在模板中可以引用{{paramName}}

someOtherHelper中,您可以使用this.paramName检索"paramValue"。 但是,当您使用{{#each nodes}}{{> child}}{{/each}}时,这意味着您将当前列表项目的内容(从LocalCursor或直接获取数组项目)作为子项的模板数据传递,并且您可以使用{{field}}引用列表项目属性在html中或在js中使用this.field

这里发生了什么是当您拨打{{> child myParam}},myParam帮助程序内容将当前节点项目覆盖为模板数据时,这就是为什么它会扰乱您的节点列表。

一个快速(肮脏)的技巧是简单地扩展myParam帮手,以便它也包含{{#each}}块的模板数据。

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> 

根据您正在努力实现的目标,可能会有更好的方法,但至少可以完成这项工作。

相关问题