我正在努力解决如果用户没有登录而将用户重定向到登录页面的常见需求(Windows 7上的Meteor v0.8.0).
stackoverflow上有几个类似的问题,但似乎没有答案对我有用.
不会工作#1:render()
从文档:
onBeforeAction: function () { if (!Meteor.user()) { // render the login template but keep the url in the browser the same this.render('login'); // stop the rest of the before hooks and the action function this.stop(); } },
这里有两个问题:
1-文档已过时.没有this.stop()
功能了.如前所述这里的代码应该是:
onBeforeAction: function (pause) { if (!Meteor.user()) { // render the login template but keep the url in the browser the same this.render('login'); // stop the rest of the before hooks and the action function pause(); } },
2-仅当路线没有时才有效layoutTemplate
.如果它有一个,login
模板将呈{{>yield}}
现在layoutTemplate
.这通常不是您想要的登录页面.
无法工作#2:Router.go()或this.redirect()
为登录页面定义路线听起来像是自然的方式.然后你可以这样做:
Router.onBeforeAction(function(pause) { if (!Meteor.user()) { pause(); Router.go('\login'); } }, {except: ['login']});
要么:
Router.onBeforeAction(function() { if (!Meteor.user()) this.redirect('\login'); }, {except: ['login']});
但奇怪的是,如果原始路线(重定向之前)具有以下内容仍然存在问题layoutTemplate
:/login
模板在内部呈现{{yield}}
.这也不是你通常想要的(并且绝对不是你所期望的,因为/login
模板没有layoutTemplate
定义).
我找到了解决这个问题的方法:
Router.onBeforeAction(function() { if (!Meteor.user()) { var that = this; setTimeout(function() { that.redirect('\login'); }, 0); } }, {except: ['login']});
现在一切都很好:/login
模板呈现为一个干净的页面......除了layoutTemplate
在/login
显示模板之前原始路径的短暂闪烁.
你有同样的问题吗?
您可以在布局模板中放置if或unless模板助手.
{{#unless currentUser}} {{> loginPage}} {{else}} {{> yield}} {{/unless}}
好的,所以似乎路由上的渲染功能只会将模板渲染到当前布局中.要将模板渲染到不同的布局,您必须调用this.setLayout('templateName')
.一个警告似乎是你需要在登录后重新设置布局.
onBeforeAction: function(pause) { var routeName = this.route.name; if (_.include(['login'], routeName)) return; if (! Meteor.userId()) { this.setLayout("newLayout"); this.render('login'); //if you have named yields it the login form this.render('loginForm', {to:"formRegion"}); //and finally call the pause() to prevent further actions from running pause(); }else{ this.setLayout(this.lookupLayoutTemplate()); } }
如果您只需要通过调用就可以获得登录模板,也可以将登录模板呈现为布局 this.setLayout('login')