Skip to content

Instantly share code, notes, and snippets.

@uvtc
Created February 24, 2017 22:38
Show Gist options
  • Save uvtc/ca819f08fe7ead81e13055f001a994e3 to your computer and use it in GitHub Desktop.
Save uvtc/ca819f08fe7ead81e13055f001a994e3 to your computer and use it in GitHub Desktop.
first attempt at sorting hiccup table rows
#!/usr/bin/env inlein
'{:dependencies [[org.clojure/clojure "1.8.0"]
[hiccup "1.0.5"]]}
(require '[hiccup.page :as hic-p])
;; Note, some :td's may contain links, or have
;; attributes, or both.
(def tbl [:table {:stuff "yo"}
[:tr
[:th "Color"]
[:th "Size"]]
[:tr
[:td [:a {:href "/red"} "red"]]
[:td {:align "right"} 2]]
[:tr {:mumble "special"}
[:td "green"]
[:td {:align "right"} 7]]
[:tr
[:td {:x "3"} [:a {:href "/blue"} "blue"]]
[:td {:align "right"} 4]]])
(defn dig-out-value
"Given a `[:td ...]`, retrieve its displayed value."
[td]
(let [x (last td)]
(if (coll? x)
(dig-out-value x)
x)))
(defn sort-table-by
"Sort the rows by the given column."
[tbl col-idx]
(let [rows' (filter #(and (coll? %)
(= :tr (first %)))
tbl)
header (first rows')
rows (rest rows')]
;; Er... I lose the orig table attribs though...
[:table
header
(sort-by #(dig-out-value (nth % col-idx))
rows)]))
(defn main
[]
(println (hic-p/html5
[:head [:title "t"]]
[:body
tbl
"\n\n" [:br] [:br] "\n\n"
(sort-table-by tbl 1)])))
;;---------
(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment