当我将旧的Iron-Router替换为Flow-Router时,我真的很想念Iron-Router定义全局可用的默认行为和设置的功能。
我知道Flow-Router使用"group"结构来定义可以应用于任何附加到该组的路由的默认挂钩事件,但似乎没有可用于定义默认模板的内容。
最佳方式是什么来实现这种类型的默认全局或组模板功能?
当我将旧的Iron-Router替换为Flow-Router时,我真的很想念Iron-Router定义全局可用的默认行为和设置的功能。
我知道Flow-Router使用"group"结构来定义可以应用于任何附加到该组的路由的默认挂钩事件,但似乎没有可用于定义默认模板的内容。
最佳方式是什么来实现这种类型的默认全局或组模板功能?
我决定使用简单的抽象方法来模拟Iron-Router的这个功能。在探索更直接地将此功能集成到FlowRouter本身之前,我正在尝试评估这是否是一种可靠且可扩展的模式,并与寻找类似解决方案的他人分享这个想法。
我只是创建了一个对象,用作参数对象模板,根据需要进行修改,然后在调用BlazeLayout.render时传递。
以下是routes.js
的示例:
var appRouteGroup = FlowRouter.group({
name: "appRouteGroup",
triggersEnter: [sometrigger]
});
var appRouteTemplates = {
menuMain: "appNav",
footerMain: "appFooter"
};
appRouteGroup.route("home", {
name: "home",
action: function () {
// We get the default templates
var templates = appRouteTemplates;
// Now we can add the route specific template
templates.content = "homePage";
// Then render with templates passed through the object param
BlazeLayout.render("mainLayout", templates);
}
});
<template name="mainLayout">
{{>Template.dynamic template=menuMain}}
{{>Template.dynamic template=content}}
{{>Template.dynamic template=footerMain}}
</template>
我在寻找一种更直接地集成FlowRouter的方式,但是它似乎已经完全可用。有没有改进的想法?
下面有更新:
我已经想出了一种相当有效和高效的方法来实现这个。
在审查Flow-Router的功能时,我注意到路由器对象包括一个字段,其中包含所有组参数,在FlowRouter.current().route.group.options
中。
该对象包含组中定义的任何键值对,无论它们是否被Flow-Router API使用。
然后我决定将其用作从组传递一些模板默认值到路由器的简单方法。
首先是组定义:
var mainRoutes = FlowRouter.group({
name: "mainRoutes",
defaultTemplates: {
menu: "mainMenu",
breadcrumb: "mainCrumb",
sidebarLeft: "sidebarLeft",
sidebarRight: "sidebarRight",
footer: "mainFooter"
}
});
接着,在定义路由时,我们可以从this.group.options.defaultTemplates
中访问这些内容。
mainAppRoutes.route('/', {
name: "home",
action: function() {
// Get the defaultTemplates object
var templates = this.group.options.defaultTemplates;
// Add route specific templates
templates.content = "homeScreen";
// Pass all the templates to the renderer
BlazeLayout.render("appLayoutMain", templates);
}
});
Router.config()
中使用模板默认值的方式,并且具有本地路由模板定义不会覆盖整个默认模板对象的附加好处。
route.action
函数中所做的那样,由于Flow-Router是非响应式的,路由器组对象似乎会从一个路由持续到另一个路由,只要这些路由在同一组中。此外,“options”对象是从路由定义传递给路由器的。因此,这意味着如果你在上面的情况下覆盖了默认参数,它将被覆盖为所有后续使用该组的路由,在调用覆盖它的路由之后。triggersExit: [ resetDefaults ]
在组定义中。function resetDefaults (context) {
context.route.group.options.defaultLayoutTemplate = "mainAppLayout";
context.route.group.options.defaultTemplates = {
defaultTeamplates: "navMain",
// ...
};
FlowRouter.current().group.parent.options.defaultTemplates
访问嵌套组的父级。 - robertdavid