Can Meteor Templates access Session variables directly?

流过昼夜 提交于 2019-12-28 09:14:38

问题


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


回答1:


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




回答2:


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



回答3:


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");
});



回答4:


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

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

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




回答5:


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




回答6:


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

{{> isCurrentUserTemplate}}


来源:https://stackoverflow.com/questions/13060608/can-meteor-templates-access-session-variables-directly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!