使用铁路由器重定向未登录的用户...再次

ste*_*643 20 meteor iron-router

我正在努力解决如果用户没有登录而将用户重定向到登录页面的常见需求(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();
  }
},
Run Code Online (Sandbox Code Playgroud)

这里有两个问题:

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();
  }
},
Run Code Online (Sandbox Code Playgroud)

2-仅当路线没有时才有效layoutTemplate.如果它有一个,login模板将呈{{>yield}}现在layoutTemplate.这通常不是您想要的登录页面.

无法工作#2:Router.go()或this.redirect()

为登录页面定义路线听起来像是自然的方式.然后你可以这样做:

Router.onBeforeAction(function(pause) {
    if (!Meteor.user()) {
        pause();
        Router.go('\login');
    }
}, {except: ['login']});
Run Code Online (Sandbox Code Playgroud)

要么:

Router.onBeforeAction(function() {
    if (!Meteor.user())
        this.redirect('\login');
}, {except: ['login']});
Run Code Online (Sandbox Code Playgroud)

但奇怪的是,如果原始路线(重定向之前)具有以下内容仍然存在问题layoutTemplate:/login模板在内部呈现{{yield}}.这也不是你通常想要的(并且绝对不是你所期望的,因为/login模板没有layoutTemplate定义).

我找到了解决这个问题的方法:

Router.onBeforeAction(function() {
    if (!Meteor.user()) {
        var that = this;
        setTimeout(function() { that.redirect('\login'); }, 0);
    }
}, {except: ['login']});
Run Code Online (Sandbox Code Playgroud)

现在一切都很好:/login模板呈现为一个干净的页面......除了layoutTemplate/login显示模板之前原始路径的短暂闪烁.

你有同样的问题吗?

Lak*_*ect 21

您可以在布局模板中放置if或unless模板助手.

{{#unless currentUser}}
  {{> loginPage}}
 {{else}}
  {{> yield}}
{{/unless}}
Run Code Online (Sandbox Code Playgroud)

  • 最优雅的解决方案,因为它简化了使用Iron Router时的复杂性,如果更新了'Meteor.user`,则无需进行反应性重新路由. (5认同)

Kel*_*ley 9

好的,所以似乎路由上的渲染功能只会将模板渲染到当前布局中.要将模板渲染到不同的布局,您必须调用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());
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您只需要通过调用就可以获得登录模板,也可以将登录模板呈现为布局 this.setLayout('login')