10

I need to build style info within hiccup in order to place an element at a location indicated by the variables "top" and "left". My code looks like so:

(html [:div {:style (str "top" top ";left" left)} "some text"])

This code is pretty ugly. It would be nicer if hiccup automatically rendered the "style" attribute using standard CSS style rules... Then I could write the following:

(html [:div {:style {:top top :left left}} "some text"])

Is there already a library that does this? Or, do I need to roll my own solution?

Thank you Clojurians for any pointers!

drcode
  • 3,287
  • 2
  • 25
  • 29

3 Answers3

11

You could write a function that would do that, and it would even be slightly less typing than the map. For example:

(defn style [& info]
  {:style (.trim (apply str (map #(let [[kwd val] %]
                                   (str (name kwd) ":" val "; "))
                                (apply hash-map info))))})

Which would allow you to write it like this...

(html [:div (style :top top :left left) "some text"])

Sample output from the function...

user=> (style :top 32 :left 14)
{:style "top: 32; left: 14;"}
BillRobertson42
  • 12,602
  • 4
  • 40
  • 57
1

What about this:

(defn style [s]
  (str/join ";" (map #(str (name %) ":" ((keyword %) s)) (keys s))))

(style {:padding     "20px"
        :background  "#e68a00"
        :color       "white"
        :font-size   "large"
        :font-weight "bold"})
0

Not much into Clojure yet, but a 'transformation' based approach like that of Enlive sounds like the solution for these kind of needs - https://github.com/cgrand/enlive

Gokul
  • 2,306
  • 2
  • 17
  • 10