Keywords with Hiccup

Isn't it nice when a hunch turns out to be a supported feature?

September 30, 2021

You can't really write very much ClojureScript without needing to work with HTML. HTML is just a document with an XML-like structure (The ML in both acronyms stands for "mark-up language"). The general structure of HTML could be represented in other formats, like JSON...or, since we're dealing with ClojureScript, why not use EDN?

And that's the premise of Hiccup, a library that can convert EDN structures into HTML documents. So, instead of this:

  <input type="radio" id="my-id" name="group" value="something">
  <label for="my-id">Something</label>

In ClojureScript (when using Hiccup), we'd declare the same structure like this:

 [:input {:type :radio :id "my-id" :name "group" :value "something"}]
 [:label {:for "my-id"} "Something"]]

What if we wanted to assign a class?

 [:input {:type :radio :class "my-class" ...}]
 [:label {:for "my-id"} "Something"]]

Easy, but what if we are adding the class programmatically, based on const values...could we use keywords (which are often used as simple constants in clojure) or must we use (name keyword)?

 [:input {:type :radio :class :my-class ...}]
 [:label {:for "my-id"} "Something"]]

It turns out that you can just use keywords as simple, string values! It's nice when a hunch based on idiomatic conventions turns out to be a supported feature. Normally, hiccups* are frustrating, but not in this case!

* A hiccup is a spasmatic inhalation with closure of the glottis, accompanied by a peculiar sound. --Lt. Commander Data