Clojure Noir路由优先

时间:2012-10-01 21:24:57

标签: clojure routing routes noir

我正在使用Noir处理Web应用程序。但是,我遇到了路由问题。这是我的控制器的代码示例:

(defpage [:get "/users/add"] []
    (common/layout
      [:div.row
       [:div.span12
        [:div.page-header
         [:h2 "Add User"]]
        (form-to {:class "form-horizontal"} [:post "/users/add"]
         (user-form {:id ""
                    :first_name ""
                    :last_name ""
                    :login ""
                    :email ""
                    :admin false
                    :staff false
                    :manager false
                    :customer false})
         [:div.control-group
          [:div.controls
           (submit-button {:class "btn btn-primary"} "Edit")]])]]))


(defpage [:get "/users/:id" :id #"\d+"] {:keys [id]}
(let [user (user/get-by-id id)]
    (common/layout
      [:div.row
       [:div.span12
        [:div.page-header
         [:h2 "View User"]]
        [:h3 (str (user :first_name) " " (user :last_name))]
        [:dl.dl-horizontal
         [:dt "login"]
         [:dd (user :login)]
         [:dt "e-mail"]
         [:dd (user :email)]
         [:dt "admin"]
         [:dd (if (user :admin) [:i.icon-ok ""] [:i.icon-remove ""])]
         [:dt "staff"]
         [:dd (if (user :staff) [:i.icon-ok ""] [:i.icon-remove ""])]
         [:dt "manager"]
         [:dd (if (user :manager) [:i.icon-ok ""] [:i.icon-remove ""])]
         [:dt "customer"]
         [:dd (if (user :customer) [:i.icon-ok ""] [:i.icon-remove ""])]]
        [:div.form-actions
         [:a.btn.btn-primary {:href (str "/users/" (user :id) "/edit")} "Edit"] " "
         [:a.btn.btn-danger {:href (str "/users/" (user :id) "/remove")} "Remove"] " "
         [:a.btn {:href "/users"} "All users"]]]])))

每次我请求“/ users / add”时,请求都被路由到“/ user /:id”(当我删除/ user / add动作时,这很好)。我有另一个控制器非常相似的代码,它工作正常。可能是什么问题?如何设置路由优先级?

谢谢, 亚切克

2 个答案:

答案 0 :(得分:1)

与webnoir.org上的路线教程相比,我看到您的代码略有不同。

此致:

(defpage [:get "/users/:id" :id #"\d+"] {:keys [id]}

webnoir上:

(defpage [:get ["/user/:id" :id #"\d+"]] {:keys [id]}
               ^                      ^ 

但也许它最终没有任何区别......

答案 1 :(得分:1)

通过source code noir判断将每条路线都放入地图中,因此无法保证调度的顺序。

在noir.core中:

(defonce noir-routes (atom {}))
...
(swap! noir-routes assoc ~(keyword fn-name) 
     (~action ~url {params# :params} (~fn-name params#)))

后来在noir.server.handler:

(defn add-route-middleware [rts]
  (let [ws (all-wrappers)]
                         ;Iterates over entries in a map, no particular order
    (for [[route-name route] rts] 
      (try-wrap (ws route-name) route))))

(defn- pack-routes []
  (apply routes (concat (add-route-middleware @noir/pre-routes)
                        (add-route-middleware @noir/noir-routes)
                        (add-route-middleware @noir/post-routes)
                        @noir/compojure-routes)))

我想如果你有less then 16 routes noir使用PersistentArrayMap并且保留了排序,但是一旦越过这个边界,路由就会被破坏。我唯一的建议是使用明确的URL。

编辑:以下是关于类似问题的bug report