Getting started: Clojure Web App with Compojure and Envlive
In this article I will show you how to create a basic Clojure web application built withCompojure and Enlive. Our HTML templates will be Pure.
You can find the code for this tutorial at Github.
CREATE A PROJECT
Generate a new Compojure project using Leiningen. For more details about Leiningen, check an older Clojure App 101 article.
is a Leiningen configuration. It stores project metadata: its dependencies, description, version et al.
In
directory we put assets such as images, JavaScript and CSS files along with HTML templates. and usually have similar structure, the first directory stores the actual application code while the second one the tests that goes with it.Run the application
Check if it works
ROUTES WITH COMPOJURE
Compojure is a routing library built on top of Ring. Routes are defined in
using macro. This macro creates a Ring handler for routes defined inside it. Each route consists of a method name ( , , ...), a path, a list of arguments (which may be empty) and a response.In our example we have 3 routes.
and are special routes, the 1st serves resources from the classpath and the 2nd returns 404 for undefined route paths.TEMPLATES WITH ENLIVE
In the presentation layer we will use pure HTML files - no cutom templating language, not even single 'staches. Data will be put into that HTML using transformations defined with Enlive. This way the design will be kept separated from the code that implements the behaviour for the display.
Add
as a project dependency in .Create a template function inside
Enlive provides a
macro which allows to specify a list of elements along with their transformations for a given HTML file. In our example we set the content of a tag with identifier to a value passed to the template definition as a parameter.Last piece of the puzzle is the actual HTML file. Create it under
as .Finally, run it as follows
Go to
to see the application in action.