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

 0鞋包控0 发布于 2023-01-17 11:52

我正在努力解决如果用户没有登录而将用户重定向到登录页面的常见需求(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显示模板之前原始路径的短暂闪烁.

你有同样的问题吗?

2 个回答
  • 您可以在布局模板中放置if或unless模板助手.

    {{#unless currentUser}}
      {{> loginPage}}
     {{else}}
      {{> yield}}
    {{/unless}}
    

    2023-01-17 11:53 回答
  • 好的,所以似乎路由上的渲染功能只会将模板渲染到当前布局中.要将模板渲染到不同的布局,您必须调用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')

    2023-01-17 11:55 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有