Append to an attribute in Enlive

纵然是瞬间 提交于 2019-12-19 09:46:53

问题


Is it possible to append a value to an attribute using enlive?

example: I have this

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

and would like this

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

I am currently doing this:

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

But I would prefer not to embed the URL into my code, by just appending the id to the existing URL

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

回答1:


@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")



回答2:


You could always write your own append-attr in the same vein as set-attr. Here is my attempt

(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))))

Which gives the following, when appending "/bar" to href, on enlive's representation of <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"}


来源:https://stackoverflow.com/questions/12586849/append-to-an-attribute-in-enlive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!