meteormeteor-blazespacebarsmeteor-helper

Meteor: Access Template Helper (or variable) from another helper


How can I reference a template helper from another one? For example...

Template.XXX.helpers({
    reusableHelper: function() {
        return this.field1 * 25 / 100; //or some other result
    },
    anotherHelper: function() {
        if (this.reusableHelper() > 300) //this does not work
            return this.reusableHelper() + ' is greater than 300'; 
        else
            return this.reusableHelper() + ' is smaller than 300';
    }
});

I have also tried Template.instance().__helpers.reusableHelper - all with no luck.

Alternatively is there a way to define reactive Template instance variables?

XXX is a sub-template that renders multiple times on the same page.


Solution

  • This like using of common code, you can make another javascript function which contains the your reusable code and call it from wherever you required.

    Like in your code-

    function calcField(field){
       return field * 25 / 100
    }
    

    and in you template helper-

    Template.XXX.helpers({
        reusableHelper: function() {
            return calcField(this.field1); 
        },
        anotherHelper: function() {
            if (calcField(this.field1) > 300) 
                return calcField(this.field1) + ' is greater than 300'; 
            else
                return calcField(this.field1) + ' is smaller than 300';
        }
    });
    

    and

    Alternatively is there a way to define reactive Template instance variables?

    you can use Session variables or Reactive variable