Repetitive structure in Clojure

212 views Asked by At

It is said in the book "Web Development with Clojure" that the code

(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"))))

can be rewritten using a helper function as following:

(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"))))

My question is: In the alternative code, why the value of the parameter name is not a string? For example, why is it (control text-field :id "screen name"), not (control text-field "id" "screen name") ?

1

There are 1 answers

0
Chiron On BEST ANSWER

I'm not familiar with Hiccup and I don't have the book you mentioned. But by reading Hiccup source code, you can find:

Label is calling make-id function which it calls as-str. Have a look at that function and see what it is doing.

(defn ^String as-str
  "Converts its arguments into a string using to-str."
  [& xs]
  (apply str (map to-str xs)))

That will leads you to ToString protocol.

Pass strings instead of keywords in the snippet you posted and see what is happening!

Source code is the best documentation we can have!