Skip to content

Syntax

Michael Randers-Pehrson edited this page Mar 25, 2015 · 17 revisions
Clone this wiki locally

Basic Syntax

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</a>

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 an ID on its own, or a class 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])]

Note that while lists are considered to be seqs by Clojure, vectors and sets are not.

Something went wrong with that request. Please try again.