In my Meteor app I find myself writing a lot of things like:
Templates.myTemplate1.isCurrentUser = function() { return Session.get("isCurrentUser"); }; Templates.myTemplate2.isCurrentUser = function() { return Session.get("isCurrentUser"); };
I need many different templates (I'm using handlebars) to access the same simple value stored inside Session.
Is there a way to avoid writing the same function over and over again? Thanks
Building on @cioddi's answer, as you can pass parameters to the Handlebars helpers, you could make it a generic function so that you can easily retrieve any value dynamically, e.g.
Template.registerHelper('session',function(input){ return Session.get(input); });
You can then call it in your template like this
{{session "isCurrentUser"}}
Note that the auth packages come with a global helper named CurrentUser that you can use to detect if the user is logged in:
{{#if currentUser}} ... {{/if}}
As meteor is currently using handlebars as default templating engine you could just define a helper for that like:
if (Meteor.isClient) { Template.registerHelper('isCurrentUser',function(input){ return Session.get("isCurrentUser"); }); }
you can do this in a new file e.g. called helpers.js to keep the app.js file cleaner. Once this helper is registered you can use it in any template by inserting {{isCurrentUser}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With