barista icon indicating copy to clipboard operation
barista copied to clipboard

Generate url by name

Open misterjt opened this issue 10 years ago • 3 comments

Can i generate URL by name?

misterjt avatar Apr 07 '14 22:04 misterjt

I really need it

misterjt avatar Apr 07 '14 22:04 misterjt

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... :)

JeanSebTr avatar Apr 09 '14 02:04 JeanSebTr

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:)

misterjt avatar Apr 10 '14 13:04 misterjt