Learning Clojure — day 7

Since my main focus are web applications I use Clojure for same purpose. That means I need to find common libraries for building basic functionality of any web application: sessions, routing and rendering html

From what I read so far you should not use monolithic framework like Rails in Clojure world. Instead you build your application from small libraries that serve certain purpose.

Compojure: routing for your application

Simple and elegant defining of routes in your application

(defroutes app-routes
(GET "/" [] "Hello World")
(POST "/login" [email password]
(handle-login email password)))

Compojure also allows you to generate skeleton for your application with

lein new compojure hello-world

It will give you few directories and files you need for your journey.

Repo — https://github.com/weavejester/compojure

Ring: http server abstraction

It will start your application at port 3000 with command

lein ring server

And give you a lot of tools for working with request and response.

(response "Hello World")

=> {:status 200
:headers {}
:body "Hello World"}

Repo — https://github.com/ring-clojure/ring

Hiccup: rendering HTML

It will allow you to generate html with Clojure code.

(html [:div {:class "foo"} "bar"]) 
=> "<div class=\"foo\">bar</div>"

With hiccup you don’t need separate template files. In example below we get users from database and render them in rows:

(defn users []

(defn user-row [user]
[:li (:name user)])

(defn users-page []
(map user-row users)]))

Repo — https://github.com/weavejester/hiccup

Feels good

This 3 libraries allows us to make a web application that dynamically render html. It is a bit more work in compare to Rails or other all-in-one frameworks but you will be surprised by how clean and flexible your code looks. WIN.

Originally published at blog.dzaporozhets.me on July 14, 2015.