Idiomatic way of rendering style info using Clojure Hiccup
Asked Answered
S

3

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!

Stuartstub answered 1/10, 2012 at 19:30 Comment(0)
C
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;"}
Cha answered 3/10, 2012 at 4:36 Comment(6)
Thanks Bill- I think it's clear from the few responses to this question that "rolling your own solution" is the right answer, as you suggest. I asked because I am creating a clojure library that adds this feature and wanted to make sure I wasn't "reinventing the wheel".Stuartstub
@Stuartstub I just realized who you are. I have Land of Lisp and I love it. Thanks!Cha
Coming across this 3 years later... the code after (name kwd) should be ":" not an empty space to be valid css syntax for any future readers.Phosphine
@ScottMitchell So it should be (str (name kwd) ":" val "; ")) instead of (str (name kwd) " " val "; ")) ?Cha
Yea I just used your snippet for an email thing ;)Phosphine
@ScottMitchell Fixed that. Thanks!Cha
S
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"})
Sadie answered 4/8, 2017 at 2:46 Comment(0)
L
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

Leatherette answered 21/11, 2013 at 17:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.