George Strakhov
George Strakhov

Reputation: 616

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

Upvotes: 26

Views: 13968

Answers (6)

WispyCloud
WispyCloud

Reputation: 4230

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

Upvotes: 46

cioddi
cioddi

Reputation: 772

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

Upvotes: 27

Nick Budden
Nick Budden

Reputation: 641

You'll want to check out these handlebar helpers for meteor: https://github.com/raix/Meteor-handlebar-helpers

There's a number of session helpers, one which does what you want. From the docs:

Is my session equal to 4?: {{$.Session.equals 'mySession' 4}}

Upvotes: 5

mjkaufer
mjkaufer

Reputation: 4216

Just a heads up to everyone: With the release of 0.8.0, Handlebars.registerHelper has become deprecated. Using the new Blaze engine, UI.registerHelper would be the new method of accomplishing this.

Updated version of @cioddi 's code

UI.registerHelper('isCurrentUser',function(input){
  return Session.get("isCurrentUser");
});

Upvotes: 12

George Katsanos
George Katsanos

Reputation: 14195

Actually now you can just use {{#if currentUser}}

It's a global included from the accounts/auth package..

http://docs.meteor.com/#template_currentuser

Upvotes: 5

Andreas
Andreas

Reputation: 1622

You could add a isCurrentUserTemplate and include this in your other templates with

{{> isCurrentUserTemplate}}

Upvotes: 1

Related Questions