Search code examples
clojureurl-routingring

How would I implement functionality similar to Rails' url_for with Clojure and its web frameworks?


I'm developing a web application with Clojure, currently with Ring, Moustache, Sandbar and Hiccup. I have a resource named job, and a route to show a particular step in a multi-step form for a particular job defined like this (other routes omitted for simplicity):

(def web-app
  (moustache/app
   ;; matches things like "/job/32/foo/bar"
   :get [["job" id & step]
         (fn [req] (web.controllers.job/show-job id step))]))

In the view my controller renders, there are links to other steps within the same job. At the moment, these urls are constructed by hand, e.g. (str "/job/" id step). I don't like that hard-coded "/job/" part of the url, because it repeats what I defined in the moustache route; if I change the route I need to change my controller, which is a tighter coupling than I care for.

I know that Rails' routing system has methods to generate urls from parameters, and I wish I had similar functionality, i.e. I wish I had a function url-for that I could call like this:

(url-for :job 32 "foo" "bar")
; => "/job/32/foo/bar"

Is there a Clojure web framework that makes this easy? If not, what are your thoughts on how this could be implemented?


Solution

  • Noir provides something similar. It's even called url-for.