Meteor Spacebars {{#if someCondition}} shows data briefly on page refresh

人走茶凉 提交于 2019-12-02 04:41:57

You need to subscribe to Meteor.users collection, template will be rendered after Meteor.user() is created, if you won't wait for subscription page will blink because at start there is nothing in Meteor.users collection.

You can use new Meteor functionality on template where you have login field

Template.login.onCreated(function () {
  var self = this;

  self.autorun(function () {
    self.subscribe("users");
  });
});

And in HTML

{{#if Template.subscriptionsReady}}
    <!--content-->
{{else}}
    Give me a second...
{{/if}}

Of course you need to create publish named 'users'

Are you sure you're thinking about this correctly?

isUserLoggedIn: function() { // implies you're checking for the user
    var user = Meteor.user(); // if there's a user this returns true

    if(user) { // you're saying if there's a user ...
        return false; // return false
    } else{ // and if there isn't
    return true; // return true
    }
}

Basically you're saying "is the user logged in" and if yes "return false" which is making you double think. Instead, reverse your logic.

isUserLoggedOut: function() { // implies you're checking for the user
    var user = Meteor.user(); // if there's a user this returns true

    if(user) { // there is a user
        return false; // so isUserLoggedOut == false
    } else{ // and if there isn't a user
        return true; // isUserLoggedOut == true
    }
}

Now your template becomes easy

{{#if isUserLoggedOut}}
   {{>loggedOutTemplate}}
{{/if}}

You can use instead, the currentUser helper from accounts package, like this.

{{#if currentUser}}
<!-- show content -->
{{else}}
 {{> login }} <!-- render login template -->
{{/if}}

Iron Router Option.

There is also a solution in the router level, using Router.onBeforeAction.

// lib/routes.js
// Create the function to check login.
   var requireLogin = function() {
       if (! Meteor.user()) {
          this.render('login');
        } else {
          this.next(); //using this.next the iron router will render the route named on the onBefore
      }
   }

   Router.onBeforeAction(requireLogin, {only: 'theRoute});

UPDATE

Template.headerTpl.helpers({
  isLogged:function(){
   if(Meteor.user()){
      return true;
    }else{
      return false;
    }
  }
})

<template name="headerTpl">
  {{#if isLogged}}
       <h1>Welcome User</h1>
     {{else}}
       <li style="display:none;"><a href="{{pathFor 'userRegistrationFormTpl'}}" id="signup-js">Sign Up</a></li>
       <li><a href="{{pathFor 'userLoginFormTpl'}}" id="login-js">Login</a></li>
  {{/if}}
</template>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!