问题描述
想象一下,我想编写一个 Clojure 函数,它返回一个等效于 <h3>Hello</h3>
的 Hiccup 结构。
我该怎么做?
我试过了
(defn render-location-details
[cur-location]
(let []
(list :h3 "Hello")
)
)
和
(defn render-location-details
[cur-location]
(let []
[:h3 "Hello"]
)
)
但在这两种情况下都收到错误消息 (:h3 "Location X") is not a valid element name.
。
(defn generate-location-details-report
[all-locations]
(let
[
hiccup-title [:h2 "Locations"]
hiccup-body (into []
(map
render-location-details
all-locations)
)
]
(str
(html hiccup-title)
hiccup-body
)
)
)
有一个集合 all-locations
。对于它的每个元素,我想在 HTML 中创建一个部分(带有 h3
)标题(hiccup-body
),添加标题(hiccup-title
)并将所有这些转换为 HTML。
解决方法
hiccup html
函数将采用一系列标签并将它们呈现为字符串。
(let [locations ["one" "two" "three"]
title-html [[:h2 "Locations"]]
location-html (map (fn [location] [:h3 location]) locations)]
(html (concat title-html location-html)))
"<h2>Locations</h2><h3>one</h3><h3>two</h3><h3>three</h3>"
第一个 render-location-details
不起作用,因为列表不是矢量,因此 Hiccup 不会将其呈现为标签。
第二个 render-location-details
没问题,可以做你想做的事。空的 (let []
绑定是不必要的。然而,Hiccup 然后通过放置 hiccup-body (into []
感到困惑 - 它试图将您的位置标签向量理解为标签,因为就 Hiccup 而言,向量 = 标签。