Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Proof of concept: S-expressions for HTML templating in clojure
(defprotocol ToHtml
(to-html [x]))
(extend-protocol ToHtml
(to-html [s]
(clojure.string/escape s {\< "&lt;" \> "&gt;" \" "&quot;" \& "&amp;"}))
(to-html [attrs]
" " (for [[k v] attrs]
(str (name k) "=\"" (to-html (str v)) "\""))))
(to-html [[tag attrs-or-more & more]]
(if (map? attrs-or-more)
"<" tag " " (to-html attrs-or-more) ">"
(apply str (map to-html more))
"</" tag ">")
(str "<" tag ">"
(apply str (map to-html (cons attrs-or-more more)))
"</" tag ">"))))
(to-html (div {:class "foo" :id "bar"}
(h1 "Hello")
(p "Some text" (i "Italic"))))
(println (to-html '(div {:class "foo" :id "bar"}
(h1 "Hello")
(p "Some text" (i "Italic")))))
; => <div class="foo" id="bar"><h1>Hello</h1><p>Some text<i>Italic</i></p></div>
;; Then in combination with, you can do templating via syntax-quote:
(template (ul {:class "foo-list"} ~@items))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment