如何在Clojure中访问表单的各个字段?

时间:2018-05-08 05:52:35

标签: clojure compojure ring hiccup

我正在构建我的第一个Web应用程序,当用户submit表单时,我很难访问表单的各个字段。这就是我所拥有的:

(defroutes app
  (GET "/" [] homepage)
  (POST "/city" request display-city)
  (route/resources "/")
  (route/not-found "Not Found"))


(defn display-city [request]
  (html5
     [:div {:class "the-city"}
      [:h2 "ALL ABOUT YOUR CITY"]
      [:ul
       [:li "Your city is " (str request) "! That's all"]]]))

;; and here's the hiccup form:
   [:form {:action "/city" :method "post"}
    (anti-forgery-field)
    [:p "Enter your home address"]
    [:div
     [:label {:for "street-field"} "Street:"]
     [:input {:id "street-field"
              :type "text"
              :name "street"}]]
    [:div
     [:label {:for "city-field"} "City:"]
     [:input {:id "city-field"
              :type "text"
              :name "city"}]
    [:div
     [:label {:for "state-field"} "State:"]
     [:input {:id "state-field"
              :type "text"
              :name "state"}]
     [:label {:for "zip-field"} "ZIP:"]
     [:input {:id "zip-field"
              :type "text"
              :name "zip"
              :size "10"}]]
    [:div.button
     [:button {:type "submit"} "Submit"]]]])

;;当我运行上面的代码时,我可以看到通过(str request)提交的整个表单,看起来像是Clojure地图。但我无法弄清楚如何提取单个“键/值”(从该地址表单,我想提取城市),或如何以我可以使用它的方式存储这些结果。有什么想法吗?

这是一个超级基本的/city页面,我试图在构建更大的东西之前了解其工作原理。谢谢!

1 个答案:

答案 0 :(得分:3)

request地图中,应该有一个键:form-params,其中包含已发布的键/值对映射。以下是您如何获得个人价值的信息:

(get-in request [:form-params :city])

或者您可以将:form-params地图解构为一次绑定多个值:

(let [{:keys [city state zip]} (:form-params request)]
  (format "%s, %s %s" city state zip))