I have tried this a couple different ways and they both behave the same way (see below for code). I\'m using a spacebars if condition (and tried using a helper as well) to check
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>
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'