barista
barista copied to clipboard
Generate url by name
Can i generate URL by name?
I really need it
I suppose you want to use something similar to named routes in rails ?
barista doesn't support that out of the box, but you could easily make a wrapper around router.url by storing the corresponding route_name -> router.url's params
in an object
var named_routes = {
post: {controller: "post", action: "getOne"},
/* ... */
};
function path_to(name, params) {
/* merge of passed params and `named_routes[name]` */
return router.url(params);
}
you could even automatically register view helpers for your named routes. Cool project that it would be... :)
Thank you, JeanSebTr, but i've already wrote my own implementation of this function with blackjack and hookers) It would be nice if you apply this in barista router
Router.prototype.generate=function(name,params, add_querystring){
var qs, route, url, _i, _len, _ref;
url = false;
_ref = this.routes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
route = _ref[_i];
if(route.route_name!==name)continue;
if (url = route.stringify(params)) {
break;
}
}
if (!url) {
return false;
}
qs = qstring.stringify(url[1]);
if (add_querystring && qs.length > 0) {
return url[0] + '?' + qs;
}
return url[0];
}
And, i have superficially studied the router and noticed that the routes are stored in the numbered array. It will be twice faster if store routes in key-value object, where key is name of route. Hope you will hear me:)