在"Web开发与Clojure"一书中所说的代码
(defn registration-page []
(layout/common
(form-to [:post "/register"]
(label "id" "screen name")
(text-field "id")
[:br]
(label "pass" "password")
(password-field "pass")
[:br]
(label "pass1" "retype password")
(password-field "pass1")
[:br]
(submit-button "create account"))))
Run Code Online (Sandbox Code Playgroud)
可以使用辅助函数重写如下:
(defn control [field name text]
(list (on-error name format-error)
(label name text)
(field name)
[:br]))
(defn registration-page []
(layout/common
(form-to [:post "/register"]
(control text-field :id "screen name")
(control password-field :pass "Password")
(control password-field :pass1 "Retype Password")
(submit-button "Create Account"))))
Run Code Online (Sandbox Code Playgroud)
我的问题是:在替代代码中,为什么参数名称的值不是字符串?例如,为什么(控制文本字段:id "屏幕名称"),而不是(控制文本字段"id" "屏幕名称")?
我不熟悉Hiccup,我没有你提到的那本书.但是通过阅读Hiccup源代码,您可以找到:
Label正在调用make-id函数,它调用as-str.看看那个功能,看看它在做什么.
(defn ^String as-str
"Converts its arguments into a string using to-str."
[& xs]
(apply str (map to-str xs)))
Run Code Online (Sandbox Code Playgroud)
这将引导您使用ToString协议.
在您发布的代码段中传递字符串而不是关键字,看看发生了什么!
源代码是我们可以拥有的最佳文档!