Clojure and me has moved.

Monday, January 19, 2009

Enlive: yet another HTML templating library

This post has moved, go to its new location
[UPDATE] I have rewritten Enlive, this posts doesn't work with the actual Enlive.
Enlive is a selector based templating library.
Its main design goal is to decouple html and presentation code, that's why Enlive templates are plain old html files (it will ease roundtripping with designers).
In code, you have to declare where (using CSS-like selectors) and how (using clojure code) to alter the html template.
The resulting templating functions are compiled (the html tree isn't transformed at runtime) and yields a seq of strings.

Here is an example:
(deftemplate microblog-template "net/cgrand/enlive_html/example.html" [title posts]
[:title] title
[:h1] title
[:div.no-msg] (when-not (seq posts) ~(html/show))
[:div.post] (for [{:keys [title body]} posts]
~(at
[:h2] title
[:p] body)))

;; at the repl:
net.cgrand.enlive-html.examples=> (apply str (microblog-template "Hello user!"
[{:title "post #1"
:body "hello with dangerous chars: <>&"}
{:title "post #2"
:body "dolor ipsum"}]))

"<html><head><title>Hello user!</title></head>
<body><h1>Hello user!</h1>
<div class=\"post\"><h2>post #1</h2>
<p>hello with dangerous chars: &lt;&gt;&amp;</p></div>
<div class=\"post\"><h2>post #2</h2>
<p>dolor ipsum</p></div></body></html>"
(NB: manually edited to add linebreaks.)

(Disclaimer: original idea by Ozzilee)

2 comments:

Ozzi said...

Holy cats, it's kind of disturbing to finally be catching up on blogs and find your own name in one of them.

Haven't had time to dig into Enlive yet, but I surely will.

Christophe Grand said...

Hi Ozzi! Good to know you are still around (and that your website is back online).