Skip to content
weavejester edited this page Nov 26, 2010 · 17 revisions

Hiccup turns Clojure data structures like this:

[:a {:href "http://github.com"} "GitHub"]

Into strings of HTML like this:

<a href="http://github.com">GitHub</div>

Using the hiccup.core/html macro.

The Clojure data structure is a vector that takes one of the following forms:

[tag & body]
[tag attributes & body]

The first item in the vector is the tag name. It is mandatory, and should be a keyword, string or symbol.

The second item may optionally be a map of attributes.

All subsequent items in the vector are treated as the element body. This can include strings or nested tag vectors, for example:

[:p "Hello " [:em "World!"]]

CSS-style sugar

Hiccup provides a convenient shortcut for adding id and class attributes to an element. Instead of writing:

[:div {:id "email" :class "selected starred"} "..."]

You can write:

[:div#email.selected.starred "..."]

As in CSS, the word after the "#" denotes the element's ID, and the word after each "." denotes the element's classes.

There may be multiple classes, but there can only be one ID. Additionally, the ID must always come first, so div#foo.bar would work, but div.foo#bar would not.

You can add a class on its own, or an ID on its own:

[:div#post "..."]
[:div.comment "..."]

Expanding seqs

If you include a Clojure seq in the body of an element vector:

[:div (list "Hello" "World")]

This is equivalent to:

[:div "Hello" "World"]

In other words, the seq is "expanded" out into the body. This is particularly useful for macros like for:

[:ul (for [x coll] [:li x])]
Clone this wiki locally