Skip to content

Instantly share code, notes, and snippets.

Last active December 14, 2015 19:49
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Compojure example with Enlive template inheritance
(ns list.handler
(:use compojure.core
[net.cgrand.enlive-html :as html])
(:require [compojure.handler :as handler]
[compojure.route :as route])
(defmacro maybe-substitute
([expr] `(if-let [x# ~expr] (html/substitute x#) identity))
([expr & exprs] `(maybe-substitute (or ~expr ~@exprs))))
(defmacro maybe-content
([expr] `(if-let [x# ~expr] (html/content x#) identity))
([expr & exprs] `(maybe-content (or ~expr ~@exprs))))
(deftemplate base-view "views/base.html"
[{:keys [content]}]
[:#content] (maybe-substitute content))
(html/defsnippet test-view "views/test.html" [:div#content]
[{:keys [left middle right]}]
[:div#left] (maybe-substitute left)
[:div#middle] (maybe-substitute middle)
[:div#right] (maybe-substitute right))
(html/defsnippet user-view "views/user.html" [:div#content]
[{:keys [id]}]
[:span#user-id] (maybe-substitute id))
(defn render
([tmpl] (tmpl {}))
([tmpl repl]
(base-view {:title "Clojure List"
:content (tmpl repl)})))
(defroutes app-routes
(GET "/test" [] (render test-view {}))
(GET ["/user/:id", :id #"[0-9]+"] [id] (render user-view {:id id}))
(route/not-found "Not Found"))
(def app
(handler/site app-routes))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment