Can Meteor Templates access Session variables directly?

后端 未结 6 1923
误落风尘
误落风尘 2020-12-08 04:44

In my Meteor app I find myself writing a lot of things like:

Templates.myTemplate1.isCurrentUser = function() {
  return Session.get(\"isCurrentUser\");
};

         


        
相关标签:
6条回答
  • 2020-12-08 05:15

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

    0 讨论(0)
  • 2020-12-08 05:23

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

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

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

    0 讨论(0)
  • 2020-12-08 05:23

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

    {{> isCurrentUserTemplate}}
    
    0 讨论(0)
  • 2020-12-08 05:24

    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");
    });
    
    0 讨论(0)
  • 2020-12-08 05:26

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

    0 讨论(0)
  • 2020-12-08 05:35

    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}}
    
    0 讨论(0)
提交回复
热议问题