If this all goes successfully we have a project ready to work with. Working with Clojure is made a lot easier if you have a working REPL to interact with, create a file called clj in the project directory containing a script like this:

This contains two functions, the router function generates different pages dependent on the requested uri and the app function that forwards a request to the router. We can test this code with a unit test, edit the file test/sprout/core_test.clj and make it look like this:

So far this is pure functional Clojure with no real web pages in site, just a map being passed into a function and a different map being returned, the maps happen to be keyed with keys that look a bit like http requests and responses. The Ring library wraps these functions with adapters that talk to real web containers we will use Jetty to demonstrate real web pages.

Create a new file in src/sprout called run.clj and edit it to appear like this:

Using a browser visit the urls http://localhost:8080, http://localhost:8080/info and http://localhost:8080/error. All being well you should see a welcome page, an info page and a 404 error.

Ring provides a further level of wrapper functions that enable html processing pipelines to be built using simple functions written in Clojure. The pages you have seen so far haven’t looked very impressive, they are not even valid HTML! We could embed the HTML in the code or write a library to generate HTML in Clojure but instead we will use Enlive.

Enlive is a selector based templating library, this differs from templating languages such as JSP or ASP in that the raw html remains untouched, functions are written that use css selectors to replace and augment the existing html. Create a file in the src/sprout directory called enlive.clj and edit it to appear like this:

The deftemplate declaration creates a template called t1, that takes no parameters and substitutes the content of any h1 tags with the word heading. The function enlive-template just applies the template to generate HTML.

Now add a new mapping to the router defined in src/sprout/core.clj to use this function, the file should now look like this:

Now go to http://localhost:8080/enlive and an HTML page should be visible.

This has been an extremely basic introduction to using Ring and Enlive with Clojure to serve up web pages. I’ll be expanding on this example at a later date to dive deeper into the functionality of Ring, Enlive and Clojure.