Ryan Neufeld

Choosing a templating language in clojure

A brief look at Enlive, Hiccup, and Selmer

One thing that is striking when working in the Clojure ecosystem is the breadth of options available to tackle any given task. The community strives to write simple, interoperable libraries and what results is a daunting number of choices, all with their own benefits and trade-offs. Templating libraries in Clojure are no exception to this rule. The Clojure Toolbox alone lists eleven template languages at last count, and it is not even an exhaustive count of the wide array of techniques available for templating web pages.

In the forthcoming Clojure Cookbook, we cover three such libraries: Enlive, Hiccup, and Selmer. Let’s take a brief look at each of these libraries and discuss their places in the ecosystem.

Hiccup—Pure data, plain and simple

Of the three libraries we’ll cover, Hiccup is the most simple of the bunch. In Hiccup, HTML tags are just vectors of Clojure data; no HTML, no template files, no interpolation (per se), just data. An HTML node is represented as a vector of three parts: tag, attributes (optional), and contents (optional, any number).

Take an anchor tag, for example:

[:a {:href "http://www.rkn.io/application-architecture"} "Application Architecture for Developers"]

Which represents the following HTML:

<a href="http://www.rkn.io/application-architecture">Application Architecture for Developers</a>

To nest multiple elements like you might do in an unordered list, replace the content portion of the vector with the additional child nodes:

[:ul {:class "groceries"}
 [:li "Apples"]
 [:li "Bananas"]
 [:li "Pears"]] ;; oh my!

Which renders as:

Read more…