One of the most basic things we do with interactive websites is submit data via the form tag. This method of input is so familiar to end users and programmers that we hardly think about it anymore. Naturally, one of the first questions I had as I started using Noir for web development was “How do I get data back from the user?”

For the most part it’s a very simple task thanks to form helpers in Hiccup (the HTML rendered that Noir houses underneath) that allow us to build what we need in much the same way we would with Ruby.

A basic example of a user registration form looks like this:

(defpartial register []
(form-to [:post "/save_user"]
(label “username” “Username:”)
(text-field “username”)
(label “password” “Password:”)
(password-field “password”)
(label “email” “Email”)
(text-field “email”)
(submit-button “Add user”)

Now there are a few things there that might bear a little explanation.

html5 tells Hiccup what to expect when rendering. There’s no real trick there and everything is taken care of by the library.

form-to takes the path to the action you’re going to post the form data to. Just like in rails this is going to be a defined route somewhere in your app. It will look like this:

(defpage [:post "/save_user"] {:as user}
(user/save_user user)
(resp/redirect “/configure”))

What I’m doing here is defining an accessible page (save_user) that defines a PersistentArrayMap (the format our data comes to us) as variable user. I then go off and save that user in a model and call resp/redirect from the library noir.response.

That was easy-peasy, and we have a form that submits our user’s input and does it all in 100% genuine Clojure.

Author’s Note: The more time I spend in Clojure, the less I think about where my parens go and how to format my code. If it looks scary now, give it a chance. It has a way of growing on you.