Enlive: yet another HTML templating library

unsorted — cgrand, 19 January 2009 @ 16 h 04 min
[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"}]))

<em>"&lt;html>&lt;head>&lt;title>Hello user!&lt;/title>&lt;/head>
&lt;body>&lt;h1>Hello user!&lt;/h1>
&lt;div class=\"post\">&lt;h2>post #1&lt;/h2>
&lt;p>hello with dangerous chars: &amp;lt;&amp;gt;&amp;amp;&lt;/p>&lt;/div>
&lt;div class=\"post\">&lt;h2>post #2&lt;/h2>
&lt;p>dolor ipsum&lt;/p>&lt;/div>&lt;/body>&lt;/html>"</em>

(NB: manually edited to add linebreaks.)

(Disclaimer: original idea by Ozzilee)

2 Comments »

  1. 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.

    Comment by Ozzi — 5 February 2009 @ 16 h 55 min
  2. Hi Ozzi! Good to know you are still around (and that your website is back online).

    Comment by Christophe Grand — 5 February 2009 @ 21 h 15 min

RSS feed for comments on this post. TrackBack URI

Leave a comment

(c) 2024 Clojure and me | powered by WordPress with Barecity