我最近一直在玩Compojure,我有一个很小的基础webapp。对于我的HTML模板,我使用Enlive,并且我有一个包含所有简单的静态页面的名称空间。对这些页面的defroute调用如下所示:
(defroutes public-routes
(GET "/" []
(info/index-template))
(GET "/about" []
(info/about-template))
(GET "/contact" []
(info/contact-template)))实际上,我得到了更多,但这应该给出我在做什么的想法。
现在,我想,这真的只是我的一堆重复,所以我想我应该尝试一下:
(defroutes info-routes
(map #(GET (str "/" %) [] (ns-resolve 'webapp.pages.info
(symbol (str % "-template"))))
'("about" "contact")))当然,这不起作用,因为map返回的是一个惰性序列,而不是一个主体(?)函数。有人知道我需要做些什么才能让这个想法起作用吗?
或者我应该使用一种完全不同的方法来减少重复自己?
发布于 2011-04-29 01:30:11
您可以始终使用defroutes使用的routes函数:
(defroutes info-routes
(apply routes
(map #(GET (str "/" %) []
(ns-resolve 'webapp.pages.info
(symbol (str % "-template"))))
'("about" "contact"))))但这仍然很无聊,让我们来增添一下情趣吧!;-)
(defn templates-for [& nss]
(->> nss
(map ns-publics)
(apply concat)
(filter #(->> % first str
(re-seq #"-template$")))
(map second)))
(defn template-uri [template]
(->> template meta :name name
(re-seq #"(.*)-template$")
first second (str "/")))
(defn template->route [template]
(GET (template-uri template) [] template))
(defroutes public-routes
(GET "/" [] "foo")
(apply routes (map template->route
(templates-for 'webapp.pages.info))))使用这段代码,templates-for函数将在给定的名称空间中查找任何以"-template“结尾的函数,并使用它们编写适当的路由。看我没有使用任何宏,而是使用了大量的合成。
https://stackoverflow.com/questions/5812117
复制相似问题