documentcloud/backbone — Issue #951: Reverse lookup of Router routes? ("urlFor")
Author: foca
Created: 2012-02-03 20:11:41+00:00
State: open

As a bit of introduction, I generate a lot of views with javascript, and I'm forced to write URLs in my handlebars templates that I would rather not have there. For this, it's important for me to ask the app "what's the URL for viewing this thing", so I hacked up this function in my Router:

``` javascript
urlFor: function(route) {
function wrapArray(obj) { return _.isArray(obj) ? obj : Array(obj) };

var params = 2 <= arguments.length ? Array.prototype.slice.call(arguments, 1) : [];

var path = _.detect(_.keys(this.routes), function(key) {
return this.routes[key] === route;
}, this);

var param;
for (var i = 0, len = params.length; i < len; i++) {
if (_.isArray(params[i]))
param = _.map(params[i], encodeURIComponent).join("/");
else
param = encodeURIComponent(params[i]);

path = path.replace(/(?:\:|\*)[^\/]+/, param);
}

return path;
}
```

That is a very contrived implementation that suits my application (it has no error handling, for example :)), but if there's interest in having something like this in Backbone proper I can work on a real patch with tests.