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:
我需要在打嗝内建立样式信息,以便将元素放在变量“top”和“left”所指示的位置。我的代码看起来像这样:
(html [:div {:style (str "top" top ";left" left)} "some text"])
(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:
这段代码非常难看。如果打嗝使用标准的CSS样式规则自动呈现“样式”属性会更好...然后我可以编写以下内容:
(html [:div {:style {:top top :left left}} "some text"])
(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!
感谢Clojurians任何指针!
3 个解决方案
#1
7
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;"}
#2
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"})
#3
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
目前还没有进入Clojure,但像Enlive那样基于“转型”的方法听起来像是满足这些需求的解决方案 - https://github.com/cgrand/enlive
#1
7
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;"}
#2
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"})
#3
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
目前还没有进入Clojure,但像Enlive那样基于“转型”的方法听起来像是满足这些需求的解决方案 - https://github.com/cgrand/enlive