3

是否可以使用 enlive 将值附加到属性?

例子:我有这个

<a href="/item/edit/">edit</a>

并且想要这个

<a href="/item/edit/123">edit</a>

我目前正在这样做:

(html/defsnippet foo "views/foo.html" [:#main]
  [ctxt]
  [:a] (html/set-attr :href (str "/item/edit/" (ctxt :id))))

但我不希望将 URL 嵌入到我的代码中,只需将 id 附加到现有 URL

(html/defsnippet foo "views/foo.html" [:#main]
  [ctxt]
  [:a@href] (html/append (ctxt :id)))
4

2 回答 2

6

@ddk answer is spot on but you may prefer a more generic way to solve the problem

(defn update-attr [attr f & args]
    (fn [node]
      (apply update-in node [:attrs attr] f args))))

and then

(update-attr :href str "123")
于 2012-10-02T08:51:25.627 回答
5

你总是可以append-attrset-attr. 这是我的尝试

(defn append-attr
  [& kvs]
    (fn [node]
      (let [in-map (apply array-map kvs)
            old-attrs (:attrs node {})
            new-attrs (into {} (for [[k v] old-attrs] 
                                    [k (str v (get in-map k))]))]
        (assoc node :attrs new-attrs))))

当附加"/bar"到时href,它给出了以下关于 enlive 的表示<a href="/foo">A link</a>

((append-attr :href "/bar") 
  {:tag :a, :attrs {:href "/foo"}, :content "A link"})
;=> {:tag :a, :attrs {:href "/foo/bar"}, :content "A link"}
于 2012-09-25T18:03:27.150 回答