Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Meteor Templates access Session variables directly?

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

like image 641
George Strakhov Avatar asked Oct 25 '12 02:10

George Strakhov


2 Answers

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}} 
like image 110
WispyCloud Avatar answered Oct 12 '22 06:10

WispyCloud


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}}

like image 38
cioddi Avatar answered Oct 12 '22 04:10

cioddi