Search code examples
javascriptmeteormeteor-helper

How to call a template helper from within the same file?


I have the following helper function:

Template.modal.helpers({ 
  permalink: function() {
    var this_id = Session.get("pageId");
    var thisItem = Items.findOne({_id: this_id});
    // console.log("set page id to " + this._id)
    return thisItem['permalink'];
  }
});

I want to call this within the same file, I tried

permalink();
this.permalink();

It didn't work so how do I use this function?


Solution

  • If you manage to call a helper "manually", it won't be easy or pretty. What you want to do is declare a regular function which can be used by both the helper and your other code, e.g.:

    function myPermalinkFunction() {
      var this_id = Session.get("pageId");
      var thisItem = Items.findOne({_id: this_id});
      // console.log("set page id to " + this._id)
      return thisItem['permalink'];
    }
    
    Template.modal.helpers({
      permalink: myPermalinkFunction
    });
    
    /* elsewhere, within the same file */
      ... myPermalinkFunction() ...
    

    In Meteor, anything declared "globally" with var or function is in fact only visible within its file, so you don't need to worry about polluting the global namespace. If you need to provide a particular context to the "helper" function, you can do so by using call or apply instead of regular invocation.