Templates 使用Iron路由器的模板内的上下文
我很难准确地理解Meteor with Iron Router调用的模板中的上下文是什么,以及这些内容是如何继承的 以下是我能想到的“我可以在双花括号内引用的东西”的所有潜在来源:Templates 使用Iron路由器的模板内的上下文,templates,meteor,Templates,Meteor,我很难准确地理解Meteor with Iron Router调用的模板中的上下文是什么,以及这些内容是如何继承的 以下是我能想到的“我可以在双花括号内引用的东西”的所有潜在来源: 内置助手 handlebar.registerHelper(…) Template.myTemplate.myVar/myHelper=… Template.myTemplate.helpers({…}) 数据:{…}内部路由(Router.map) 与#每个有关吗 与#与有关 我忘了什么吗?有全局变量吗 我想我
- 内置助手
handlebar.registerHelper(…)
Template.myTemplate.myVar/myHelper=…
Template.myTemplate.helpers({…})
内部路由(Router.map)数据:{…}
- 与
#每个
有关吗
- 与#与有关
#each
和#with
)的情况
澄清一下就好了 IronRouter使用RouteControl.data的结果作为当前数据上下文呈现模板
<template name="viewPost">
<div>
<h1>{{title}}</h1>
<p>{{content}}</p>
</div>
</template>
var PostsController=RouteController.extend({
template:"viewPost",
waitOn:function(){
return Meteor.subscribe("postsById",this.params._id);
},
data:function(){
return Posts.findOne(this.params._id);
}
});
this.route("viewPost",{
path:"/posts/:_id",
controller:PostsController
});
如您所见,带有控件的#结构设置当前数据上下文。
#each结构在游标(或数组)上迭代,并将当前数据上下文设置为当前获取的文档(或当前单元格)
现在,如果您用这个新的帮助器替换嵌套的#each,您将可以访问“内容”中的parentProperty。谢谢您的回答。你能不能加一条关于继承的注释?例如,如果我有嵌套的
#每个
块,变量是否级联?我已经更新了我的帖子,它是否回答了你的问题?一个小小的学习:外部模板上定义的模板帮助程序不会继承到嵌套模板中(当然)。是否可以从{{code>{each}}
中使用来访问父上下文?
{{#with myContext}}
{{> myTemplate}}
{{/with}}
{{> myTemplate myContext}}
<template name="postsList">
{{#each posts}}
<h1>{{title}}</h1>
{{/each}}
</template>
Template.postsList.helpers({
posts:function(){
// cursor
return Posts.find();
// array
return [{title:"Title 1"},{title:"Title 2"},{title:"Title 3"}];
}
});
<template name="parent">
<ul>
{{#each parentContexts}}
{{> child}}
{{/each}}
</ul>
</template>
<template name="child">
<li>
<ul>
{{#each childContexts}}
{{> content}}
<p>../this.parentProperty = {{../this.parentProperty}}</p>
{{/each}}
</ul>
</li>
</template>
<template name="content">
<li>
<p>this.childProperty = {{this.childProperty}}</p>
<p>this.parentProperty = {{this.parentProperty}}</p>
</li>
</template>
Template.parent.helpers({
parentContexts:function(){
return [{
parentProperty:"parent 1"
},{
parentProperty:"parent 2"
}];
}
});
Template.child.helpers({
childContexts:function(){
return [{
childProperty:"child 1"
},{
childProperty:"child 2"
}];
}
});
Handlebars.registerHelper("eachWithParent",function(context,options){
var parentContext=this;
var contents="";
_.each(context,function(item){
var augmentedContext=_.extend(item,parentContext);
contents+=options.fn(augmentedContext);
});
return contents;
});