在铁路由器中使用正则表达式时,如何访问匹配项? [英] When using a regex in iron router, how to access the match?
问题描述
我没有五个不同的路径,而是尝试将五个不同的路径组合到一个函数中,但是我仍然需要知道它匹配的路径.因此,如果我使用正则表达式设置路线:
Rather than having five different routes, I am trying to combined five different paths into a single function, but I still need to know which path it matched. So if I set up my route using a regex:
Router.route(/^\/(accounts)|(contacts)|(forecasts)|(analytics)|(activities)/, function() {
// which one did it match?
console.log("matched "+this.params) //this returns an array of five params
}
如何在函数内部引用匹配的参数?
how do I refer to the matched parameter inside the function?
this.params返回一个包含五个参数的数组,其中四个未定义,另一个匹配,但是定义哪个取决于匹配的对象,所以这不是很有用.
this.params returns an array of five params with four of them undefined and the other matching, but which one is defined depends on what matched so this isn't very helpful.
推荐答案
这是Iron.Router自定义路由控制器的典型方案!如果需要,请在此处查看指南一些代码,让我知道. ;)
This is a typical scenario for Iron.Router custom route controller! Check the guide here If you need some code, let me know. ;)
-
首先,为所有站点定义一个路由控制器,这些站点将继承 来自RouteController.
First, you define a route controller for all your sites, which inherit from the RouteController.
BaseController = RouteController.extend({
// Put repeating logic for your sites here
});
在那之后,您可以分别定义路由,而不是通过正则表达式.这是 更加模块化和可维护.这里的重点是,你不要 必须通过复杂的功能找出哪个站点是最新的.
After that, you define your routes seperatly, not via regex. This is much more modular and maintainable. The big point here is, you don't have to find out by complicated functions, which site is current.
Router.map(function(){
this.route('accounts', {
path: '/accounts'
});
});
现在,给您的路由他自己的控制器
Now, give your routes his own controller
Router.map(function(){
this.route('accounts', {
path: '/accounts',
controller: 'AccountsController'
});
});
在此示例中,您的AccountsController
需要从您的
新的BaseController
.放置所有的路线逻辑,这是特定的
仅针对此路线,在您的AccountsController
In this Example, your AccountsController
needs to inherit from your
new BaseController
. Put all your route logic, which is specific
for only this route, in your AccountsController
AccountsController = BaseController.extend({
// Put your specific route logic here
});
请确保在您的BaseController
之前是由流星加载的
路线.查看Meteor 文件加载顺序.您可以执行以下操作
Make sure, your BaseController
is loading by meteor before your
routes. Check out Meteor File Load Order.You can do something like the following
client/routes
client/routes/routes.js
client/routes/controller/AccountsController.js
client/routes/controller/BaseController.js
这篇关于在铁路由器中使用正则表达式时,如何访问匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!