如何使用iron:router建立动态路由?

How to build Dynamic Route using iron:router?

下面的代码是我们通常可以实现的路由方式

Router.route('/', function(){
  this.render("", {to: 'content'});
});

Router.route('/user/add', function(){
   this.render("templateName", {to: 'content'});
});

我只是尝试从集合中构建路线图,而不是上面的方法。例如:

var allRoutes = [{
    "name" : "userDetail",
    "path" : "/user/add",
    "template" : [
        {
            "name" : "addUser",
            "section" : "content"
        }
    ],
    "options" : null
}, {
    "name" : "default",
    "path" : "/",
    "template" : [
        {
            "name" : "default",
            "section" : "content"
        }
    ],
    "options" : null
}];

for(var i=0;i<allRoutes.length;i++){
    Router.route(allRoutes[i].path, function(){
        var templates = allRoutes[i].template;
        for(var t=0;t<templates.length;t++){
            this.render(templates[t].name, {to:templates[t].section});
        }
    });
}

路由映射的构建方式可以在浏览器控制台中看到,但在 url 出现时无法正常工作。

提前致谢。

你定义的函数在运行时间调用时有未定义的变量(allRoutes[i]只在for循环执行期间明确定义,在route函数执行期间没有) .

使用路由选项而不是函数http://iron-meteor.github.io/iron-router/#route-options:

for(var i=0;i<allRoutes.length;i++){
    var t = allRoutes[i].template[0];
    Router.route(allRoutes[i].path, {
        template: t.name;
        data: t.section);
        }
    });
}

顺便说一句,每个路由不能渲染多个模板。

 for(var i=0;i<allRoutes.length;i++){
  Router.route(allRoutes[i].path, renderTemplate(allRoutes[i].template));
 }

// it renders the templates on router callback
function renderTemplate(templates){
  return function(){
    for(var t=0;t<templates.length;t++){
      this.render(templates[t].name, {to:templates[t].section});
     }
 }
}

这是使用相应的 "Yield" Section.It 进行多模板渲染的一种方法,可以很好地处理客户端中的临时数组,但不适用于来自 MongoDB 的集合。