如何定义全局模板帮助函数?

10

在很多模板中,我想要使用相同的函数,但是它们必须在每个模板中定义。 就像这样:

function getNodesById(id){
    return collection.find({sid:id}).fetch();
}

Template.navigation.getNodesById= function(id){
    return getNodesById(id);
}

Template.body.getNodesById= function(id){
    return getNodesById(id);
}

Html:

<Template name="navigation">
... 
{{#each getNodesById '1'}}
...
{{/each}}
...
</Template>
<Template name="body">
...
{{#each getNodesById '1'}}
...
{{/each}}
...
</Template>
...
<Template name="...">
 .....
</Template>
有没有办法定义全局模板函数而不是一个模板?就像这样: 在JavaScript中:
    defined global tempele.functionA = function(...){
         return ...
    }
在HTML中:
<Template name ="a">
   {{#each  functionA ...}}
   {{/each }}
</Template>

<Template name ="b">
   {{#each  functionA ...}}
   {{/each }}
</Template>
<Template name="...">
    {{ #..  functionA ...}}
        ....
     {{/...}}
</Template >
我能做到吗?我希望我已经清楚地描述了问题。
3个回答

14
您可以直接在handlebars中注册您的helpers。这是我用于显示当前用户电子邮件地址的方法:
Handlebars.registerHelper('currentUserName', function () {
    var user = Meteor.user();
    if (_.isUndefined(user) || _.isNull(user)) {
        return new Handlebars.SafeString("<i class='icon-spin icon-spinner'></i> Login");
    }
    return user.emails[0].address;
});

在任何模板中,我只需调用{{currentUserName}}。对于您来说,它将是

Handlebars.registerHelper('getNodeById', function (id) {
    return collection.find({sid:id}).fetch();
});

顺便提一下:从您想要使用它的方式来看,您可能对Meteor的理解有误。Meteor是数据驱动的-不要试图强制执行流驱动的范例。如果您在模板中缺少某些数据,应更改数据源,而不仅仅在模板中获取数据。


谢谢您的提醒,我想我开始时可能是错的。Meteor 是数据驱动的,我会记住这一点的。谢谢! - L.T

13

自Meteor 1.0起,这里的文档指示开发人员使用Template.registerHelper来定义全局可用的模板辅助函数。

因此,在这个问题的情况下,正确的代码格式应该是这样的:

    Template.registerHelper("getNodesById", function(id) {
        return collection.find({sid: id});
    }
您可以在以下两种方式之一中的任何一个模板中引用此模板辅助程序:

1.使用双大括号({{helperName}})包含helper名称。

2.使用#helper名称标签将整个块包装在helper中。


1.使用双大括号({{helperName}})包含helper名称。

2.使用#helper名称标签将整个块包装在helper中。

    {{getNodesById '1'}}
或者
    {{#each getNodesById '1'}}
      ...
    {{/each}}

3

对于 Meteor 0.8 或更高版本,使用 UI.registerHelper 即可完成此任务。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接