使用Clojure Hiccup渲染样式信息的惯用方式

10
我需要在hiccup中构建样式信息,以便将元素放置在由变量"top"和"left"指示的位置。我的代码如下:
  

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

这段代码相当难看。如果hiccup能够自动使用标准CSS样式规则渲染"style"属性,那就更好了... 那么我可以写以下代码:
  

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

是否已经有一个库可以做到这一点?还是说我需要自己编写解决方案?
感谢Clojurians提供任何线索!
3个回答

11
你可以编写一个函数来实现这个功能,这比使用 map 要少打一些字。例如:
(defn style [& info]
  {:style (.trim (apply str (map #(let [[kwd val] %]
                                   (str (name kwd) ":" val "; "))
                                (apply hash-map info))))})

这将允许你像这样编写代码...

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

函数的示例输出...

user=> (style :top 32 :left 14)
{:style "top: 32; left: 14;"}

感谢Bill的回答-我认为从这个问题的几个回复中可以清楚地看出,“自己编写解决方案”正是你所建议的正确答案。我之所以提问,是因为我正在创建一个Clojure库,添加了这个功能,并希望确保我没有“重复造轮子”。 - drcode
@drcode 我刚意识到你是谁。我有《Lisp之国》这本书,我很喜欢它。谢谢! - BillRobertson42
三年后再看到这个问题...在 (name kwd) 后面的代码应该是 ":" 而不是空格,以便于任何未来读者能够正确理解 CSS 语法。 - Scott Mitchell
@ScottMitchell 所以应该是(str (name kwd) ":" val "; ")),而不是(str (name kwd) " " val "; "))吗? - BillRobertson42
是的,我刚刚使用了你的代码片段来处理电子邮件 ;) - Scott Mitchell
@ScottMitchell 已经修复了。谢谢! - BillRobertson42

1
这是什么意思:
(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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接