user3714488
user3714488

Reputation: 103

Meteor How to call one template helper into another helper?

How i can access one template helper into another. I have 2 templates

  1. Right sidebar path is

app\client\templates\shared\sidebar

  1. my_trb path is

app\client\templates\pages\my_trb

on my_trb page i am showing list of all added memebrs in my account and same thing i need to call in sidebar helper. So is there way to call my_trb template helper into sidebar? This is helper in my_trb

Template.MyTribes.helpers({

  'myTrb' () {
    let tribIOwn = Meteor.user().trb_i_own; 
    let trb = [];
    tribIOwn.forEach(function (t) {
      trb.push(Trb.findOne({_id: t}));
    });
    return trb;
  },

});

This is full code of tribes_controller.js

TrbController = RouteController.extend({

  subscriptions: function() {
    this.subscribe('users').wait();
    this.subscribe('trb', this.params._id).wait();
  },

  waitOn: function () {
    this.subscribe('trb',Meteor.userId());
    this.subscribe('tribeArgs', this.params._id);
  },


  data: function () {
    return Trb.findOne({_id: this.params._id});
  },

  // You can provide any of the hook options

  onRun: function () {
    this.next();
  },
  onRerun: function () {
    this.next();
  },

  //onBeforeAction: function () {
  //  this.next();
  //},
  onBeforeAction: function () {
    if (!Meteor.userId()) {
      this.render('Splash');
    } else {
      if (!Meteor.user().username) {
        this.render('AddUsername');
      } else {
        this.next();
      }
    }
  },


  action: function () {
    this.render();
  },
  onAfterAction: function () {
  },
  onStop: function () {
  },
  editTribe: function () {
    this.render('EditTribe');
  }
});

Upvotes: 0

Views: 323

Answers (1)

Jankapunkt
Jankapunkt

Reputation: 8423

For common / shared code that needs to be accessed by more than one Template it makes sense to define a global helper using Template.registerHelper.

For your helper this would look like this:

app\client\templates\shared\helpers

// import { Trb } from ....

Template.registerHelpers('myTrb', function myTrb () {
  const user = Meteor.user();
  if (! user) return [];
  const tribIOwn = user.trb_i_own; 
  const trb = [];
  tribIOwn.forEach(function (t) {
    trb.push(Trb.findOne({_id: t}));
  });
  return trb
})

(Note, that I changed a bit, since Meteor.user().trb_i_own would crash if there is no logged in user.)

Now you can remove the helper on the my_trb Template and call it from my_trb and the sidebar as well.

Upvotes: 2

Related Questions