在使用 Meteor 模板遍历数据的过程中,可能会遇到一种情况,当 each 遍历某个数据集的时候可能会用到 each 外部模板中的某些数据(或上一级数据环境的数据),类似如下代码的情况:
<template name="profile"> <h2>Profile</h2> {{#with profile}} <img src="{{avatarPath}}"/> {{#with name}} {{getDataHelper "上一级的某个数据作为参数传递"}} <p>{{fullName}}</p> {{/with}} {{/with}} </template>
我们希望在内部的 with 中访问上一层 with 的数据上下文,可以使用如下方法。
<template name="profile"> <h2>Profile</h2> {{#with profile}} <img src="{{avatarPath}}"/> {{#with name}} {{parentHelper ..}} <p>{{fullName}}</p> {{/with}} {{/with}} </template>
注意 parentHelper 后面的 .. ,这个 .. 类似于 linux 下 cd .. 的意思,回到上一级。这样传递参数后,通过 parentHelper 的 helper 函数打印一下就可以看到上一级的数据集了。
Template.profile.helpers({ parentHelper: function (parentContext) { console.log(this); // profile.name data context console.log(parentContext); // profile data context } });
文章来源:https://www.discovermeteor.com/blog/a-guide-to-meteor-templates-data-contexts/