use*_*514 3 handlebars.js meteor
我试图弄清楚如何将参数传递到每个块中的子模板,并使用子模板中的参数以及子模板帮助器.这是我到目前为止尝试的内容:
模板:
<template name="parent">
{{#each nodes }}
{{> child myParam}}
{{/each}}
</template>
<template name="child">
{{ paramName }}
</template>
Run Code Online (Sandbox Code Playgroud)
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?
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,它还没有工作,似乎在某种程度上弄乱了我的输入节点列表.
感谢帮助.
当您使用时{{> child myParam}},它会调用子模板并将其关联myParam为当前模板数据上下文,这意味着您可以在模板中引用它{{paramName}}.
在someOtherHelper你可以使用this.paramName检索"paramValue".但是,当您使用时{{#each nodes}}{{> child}}{{/each}},这意味着您传递当前列表项的内容(从一个LocalCursor或直接从数组项中获取)作为子模板数据,并且您可以{{field}}在html或this.fieldin中引用列表项属性JS.
这里发生的是当你调用时{{> 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>
Run Code Online (Sandbox Code Playgroud)
根据您正在尝试实现的目标,可能会有更好的方法,但这个方法至少可以完成工作.
| 归档时间: |
|
| 查看次数: |
5740 次 |
| 最近记录: |