Skip to content

Instantly share code, notes, and snippets.

@dlitvakb
Created June 26, 2012 19:36
Show Gist options
  • Select an option

  • Save dlitvakb/2998305 to your computer and use it in GitHub Desktop.

Select an option

Save dlitvakb/2998305 to your computer and use it in GitHub Desktop.
A little XML/xHTML templating engine for learning clojure
;; A little XML/xHTML templating engine as an excercise for learning clojure
(defn attr [a-map]
^{:doc "renders an attribute"
:test (fn []
(assert (= "class='hola'" (attr {:name "class", :value "hola"}))))}
(str (:name a-map) "='" (:value a-map) "'"))
(defn as-attr-list [ats]
^{:doc "renders a list of attributes"
:test (fn []
(assert (= "class='hola'" (as-attr-list (list {:name "class", :value "hola"}))))
(assert
(= "class='hola' href='#'"
(as-attr-list (list
{:name "class", :value "hola"}
{:name "href", :value "#"})))))}
(if (== (count ats) 1)
(str (attr (first ats)))
(str (attr (first ats)) " " (str (as-attr-list (rest ats))))
))
(defn as-tag-list [tags]
^{:doc "renders a list of tags"
:test (fn []
(assert (= "<p></p>" (as-tag-list (list (tag "p" "")))))
(assert (= "<div></div><p></p>" (as-tag-list (list (tag "div" "") (tag "p" ""))))))}
(clojure.string/join "" (map str tags)))
(defn tag
^{:doc "renders a tag with or without attributes"
:test (fn []
(assert (= "<p>text</p>" (tag "p" "text")))
(assert (= "<p class='hola'>text</p>"
(tag "p" "text" (list {:name "class", :value "hola"})))))}
([tag-name value attrs]
(str "<" tag-name " " (as-attr-list attrs) ">" value "</" tag-name ">"))
([tag-name value]
(str "<" tag-name ">" value "</" tag-name ">")))
;; A little desk test
(time (+ 1 1))
(println (as-tag-list (list (tag "div" "hey") (tag "p" "ho"))))
(println
(as-tag-list
(list
(tag "html"
(tag "body"
(tag "h1" "hola mundo!"
(list
{:name "class", :value "header"}
{:name "onclick", :value "javascript:void(0)"})))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment