如何创建一个返回 Hiccup 结构的 Clojure 函数?

问题描述

想象一下,我想编写一个 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.

更新 1:我从这个函数调用上述函数

(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 而言,向量 = 标签。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...