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

StackOverflow https://stackoverflow.com//questions/9679573

  •  13-12-2019
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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

OTHER TIPS

The example function you have mentioned could be implemented as below. But I am not sure if this is exactly what you are looking for.

(defn url-for [& rest]
    (reduce 
        #(str %1 "/" %2) "" (map #(if (keyword? %1) (name %1) (str %1)) rest)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top