gpt4 book ai didi

clojure - 从列表创建 Compoju 路由

转载 作者:行者123 更新时间:2023-12-04 11:59:49 24 4
gpt4 key购买 nike

我最近刚刚在玩 Compojure,我有一个小的基本 web 应用程序。对于我的 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")))

当然,这行不通,因为映射返回的是惰性序列而不是函数体 (?)。
有人知道我需要做什么才能让这个想法发挥作用吗?

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

最佳答案

您可以随时使用 routes defroutes 使用的函数:

(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 function 将在给定的命名空间中查找以“-template”结尾的任何函数,并用它们编写适当的路由。看看我没有使用任何宏,而是使用大量组合。

关于clojure - 从列表创建 Compoju 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5812117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com