查找 Iron Router 中定义的所有路由
Find all routes defined in Iron Router
有没有办法为 Iron Router 路由器中定义的所有路径动态添加站点地图?
我在想这样的事情:
<ul>
{{#each paths}}
<li><a href="pathFor {{route}}">{{route}}</a></li>
{{/each}}
</ul>
此外,也许相应的子路径将显示在子 ul
中?
显然我也可以手动创建列表,但对于具有 50 多个链接的应用程序来说,这是一项艰巨的工作。
当然可以!正如 Kassym 指出的那样,Router.routes
包含所有路线的列表。但是它包含路由器 功能 ,因此您必须使用 route.<b>getName()</b>
获取它们的名称。默认路由没有名称,因此您必须获取 .path()
。
在您的助手中,整个过程应该如下所示:
Template.allRoutes.helpers({
paths: function () {
var allRoutes = _.map(Router.routes, function(route){
var routeName = typeof route.getName() === 'undefined' ?
route.path() :
route.getName();
return {route: routeName}
});
return allRoutes
}
});
在您的模板中:
<template name="allRoutes">
{{#each paths}}
<li><a href="{{pathFor route}}">{{route}}</a></li>
{{/each}}
</template>
Working Demo in MeteorPad
Note: Remember to enclose pathFor
in curly brackets because it is a helper method. It will execute javascript and inherit the current datacontext, so you can pass it any property from the current context.
为了显示 n 深度的子路径,您可以像这样递归调用您的模板:
<template name="subpaths">
<ul>
{{#each subpaths}}
<li>
<a href="{{pathFor path}}">{{path}}</a>
{{#if subpaths}} {{>subpaths}} {{/if}}
</li>
{{/each}}
</ul>
</template>
有关详细信息,请参阅
有没有办法为 Iron Router 路由器中定义的所有路径动态添加站点地图?
我在想这样的事情:
<ul>
{{#each paths}}
<li><a href="pathFor {{route}}">{{route}}</a></li>
{{/each}}
</ul>
此外,也许相应的子路径将显示在子 ul
中?
显然我也可以手动创建列表,但对于具有 50 多个链接的应用程序来说,这是一项艰巨的工作。
当然可以!正如 Kassym 指出的那样,Router.routes
包含所有路线的列表。但是它包含路由器 功能 ,因此您必须使用 route.<b>getName()</b>
获取它们的名称。默认路由没有名称,因此您必须获取 .path()
。
在您的助手中,整个过程应该如下所示:
Template.allRoutes.helpers({
paths: function () {
var allRoutes = _.map(Router.routes, function(route){
var routeName = typeof route.getName() === 'undefined' ?
route.path() :
route.getName();
return {route: routeName}
});
return allRoutes
}
});
在您的模板中:
<template name="allRoutes">
{{#each paths}}
<li><a href="{{pathFor route}}">{{route}}</a></li>
{{/each}}
</template>
Working Demo in MeteorPad
Note: Remember to enclose
pathFor
in curly brackets because it is a helper method. It will execute javascript and inherit the current datacontext, so you can pass it any property from the current context.
为了显示 n 深度的子路径,您可以像这样递归调用您的模板:
<template name="subpaths">
<ul>
{{#each subpaths}}
<li>
<a href="{{pathFor path}}">{{path}}</a>
{{#if subpaths}} {{>subpaths}} {{/if}}
</li>
{{/each}}
</ul>
</template>
有关详细信息,请参阅