Skip to content

Instantly share code, notes, and snippets.

@semperos
Created February 2, 2011 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save semperos/807755 to your computer and use it in GitHub Desktop.
Save semperos/807755 to your computer and use it in GitHub Desktop.
Function using hiccup to print a Clojure map as a "nested" HTML list.
(def example-map
{:a "foo" :b "bar" :other-stuff
{:item-1 ["hello" "clojure"],
:item-2 ["hello" "hiccup"],
:another-map
{:x "foo" :y "bar" :z "baz"}}
:c "wowza sauce"})
(defn map-to-html-list
"Clojure map to nested HTML list. Optional list-type and wrapper params taken as keywords hiccup understands, and optional sep parameter for the string to show key-value associations"
([m] (map-to-html-list m :ul :span " => "))
([m list-type] (map-to-html-list m list-type :span " => "))
([m list-type wrapper] (map-to-html-list m list-type wrapper " => "))
([m list-type wrapper sep]
(html
[list-type
(for [[k v] m]
[:li
[wrapper (str k sep
(if (map? v)
(map-to-html-list v list-type wrapper sep)
v))]])])))
(map-to-html-list example-map)
;;; Default Output
;;;
;;; Probably best when wrapped in <pre> tags, which I've added here manually for copy & paste convenience
<pre><ul><li><span>:a =&gt; foo</span></li><li><span>:b =&gt; bar</span></li><li><span>:other-stuff =&gt; <ul><li><span>:item-1 =&gt; ["hello" "clojure"]</span></li><li><span>:item-2 =&gt; ["hello" "hiccup"]</span></li><li><span>:another-map =&gt; <ul><li><span>:x =&gt; foo</span></li><li><span>:y =&gt; bar</span></li><li><span>:z =&gt; baz</span></li></ul></span></li></ul></span></li><li><span>:c =&gt; wowza sauce</span></li></ul></pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment