首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从列表创建Compojure路由

从列表创建Compojure路由
EN

Stack Overflow用户
提问于 2011-04-28 08:00:40
回答 1查看 728关注 0票数 6

我最近一直在玩Compojure,我有一个很小的基础webapp。对于我的HTML模板,我使用Enlive,并且我有一个包含所有简单的静态页面的名称空间。对这些页面的defroute调用如下所示:

代码语言:javascript
复制
(defroutes public-routes
  (GET "/" []
    (info/index-template))
  (GET "/about" []
    (info/about-template))
  (GET "/contact" []
    (info/contact-template)))

实际上,我得到了更多,但这应该给出我在做什么的想法。

现在,我想,这真的只是我的一堆重复,所以我想我应该尝试一下:

代码语言:javascript
复制
(defroutes info-routes
  (map #(GET (str "/" %) [] (ns-resolve 'webapp.pages.info
                                        (symbol (str % "-template"))))
       '("about" "contact")))

当然,这不起作用,因为map返回的是一个惰性序列,而不是一个主体(?)函数。有人知道我需要做些什么才能让这个想法起作用吗?

或者我应该使用一种完全不同的方法来减少重复自己?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-04-29 01:30:11

您可以始终使用defroutes使用的routes函数:

代码语言:javascript
复制
(defroutes info-routes
  (apply routes
    (map #(GET (str "/" %) [] 
               (ns-resolve 'webapp.pages.info
                           (symbol (str % "-template"))))
         '("about" "contact"))))

但这仍然很无聊,让我们来增添一下情趣吧!;-)

代码语言:javascript
复制
(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“结尾的函数,并使用它们编写适当的路由。看我没有使用任何宏,而是使用了大量的合成。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5812117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档