Two ways to define helpers in Meteor

馋奶兔 提交于 2020-01-04 05:15:36

问题


EDIT: This is no longer relevant in Meteor 1.0. The first syntax has been deprecated, and only the second is supported.

It seems that there are two ways to define what are apparently called helpers in Meteor:

Template.foo.helper1 = function() { ... }

Other way:

Template.foo.helpers({
  helper2: function() { ... }
});

Is there any semantic or usage difference between the two? The only restriction I can see is that the first usage can't use reserved keywords. I'm wondering if the distinction arose only for historical reasons or if there is something else.


回答1:


According to http://docs.meteor.com/#template_helpers they are equivalent aside from the syntax, and the Template.myTemplate.foo syntax will not work for reserved template names.

The nice thing about using a dictionary passed to Template.myTemplate.helpers is that you can reuse it across multiple templates.

    var reusableHelpers = { stuff: function() { return "stuff"; } };
    Template.foo.helpers( reusableHelpers );
    Template.bar.helpers( reusableHelpers );



回答2:


I think what you're looking for are details in regards to handlebars, found here:

http://handlebarsjs.com/expressions.html




回答3:


As answered there: Sharing functions between templates in Meteor, with Meteor 1.0 here now, this seems to have changed. After some digging, I found that you can now use the following to reuse code between helpers:

https://docs.meteor.com/#/full/template_registerhelper

Template.registerHelper("checkedIf",function(value){
  return value?"checked":"";
});

This makes it available in all helpers!



来源:https://stackoverflow.com/questions/17099929/two-ways-to-define-helpers-in-meteor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!