How to combine same template helpers from two+ different templates?

I’m really glad to see this forum here!

I have a “submit” template and an “edit” template. The form within each template is nearly identical to the other. As a result I have helpers that are identical to each other (save field names which I could pass in at the template.)

Edit template:

Template.etoeventEdit.helpers({
  errorMessage: function (field) {
    return Session.get('etoeventEditErrors')[field];
  }
  , errorClass: function (field) {
    return !!Session.get('etoeventEditErrors')[field] ? 'has-error' : '';
  }

  ...

});

Submit template:

Template.etoeventSubmit.helpers({
  errorMessage: function (field) {
    return Session.get('etoeventEditErrors')[field];
  }
  , errorClass: function (field) {
    return !!Session.get('etoeventEditErrors')[field] ? 'has-error' : '';
  }

  ...

});

Thanks!

var formHelpers = {
    // ...
};

Template.etoeventSubmit.helpers(formHelpers);
Template.etoeventSubmit.helpers({
    // ...
});
Template.etoeventEdit.helpers(formHelpers);
Template.etoeventEdit.helpers({
    // ...
});
1 Like

Thanks, @dburles. I’ll give it a try.

Does this technique have a name?

No magic here, it’s just Javascript!

1 Like

Did you consider global helpers?

UI.registerHelper('errorMessage', function() {
  Session.get("errorMessage")[field];
});

UI was deprecated. You should use Template instead.

Template.registerHelper('errorMessage', function() {
  Session.get("errorMessage")[field];
});
1 Like

Hi @nsinenko. No, but I will now. :smile:

You should most definitely take a look at https://atmospherejs.com/aldeed/template-extension which is one of the most popular packages on atmosphere and breathes new life to templates.

You get inheritance, hooks, callbacks and an arsenal of tools to work with templates.

@serkandurusoy I have same problem like topicstarter(two+ same template helpers) and I looked to aldeed:template-extension and didn’t understand how I can deal with my problem using this extension. Can you give an example? Thanks.

There is a quite nice example in the official readme at https://github.com/aldeed/meteor-template-extension/#inheritshelpersfromtemplatename-inheritseventsfromtemplatename-and-inheritshooksfromtemplatename

Basically what Template.myTemplate2.inheritsHelpersFrom("myTemplate1"); does is create an exact clone of the helpers from myTemplate1 on myTemplate2

@serkandurusoy thank you. I supposed that exists another way to do it, not cloning. I solve it by define global helper )

Since helpers often go along with a specific collection, it could be a good idea to attach them to that collection instead of a template, using https://github.com/dburles/meteor-collection-helpers

Then whenever you use that collection in a template you’ll have access to them just like template helpers. And you can also do stuff like this: Collection.findOne('id').myLittleHelper()