Search code examples
clojureenlive

Update and normalize attr src in enlive


I just start programming recently and I have this problem, so I have this html snippet. I want parse the src attribute of the img and normalize it with urly path normalization, and add some new path to the src.

<html>
<body>
    <div class="content">lorem ipsum
        <img style="margin-top: -5px;" src="/img/car.png" />
    </div>
    <img style="margin-top: -5px;" src="/img/chair.png" />
</body>
</html>

become this

<html>
<body>
    <div class="content">lorem ipsum
        <img style="margin-top: -5px;" src="/path1/img/car.png" />
    </div>
    <img style="margin-top: -5px;" src="/path1/img/chair.png" />
</body>
</html>

I think of this method but i just can't find the way to acquire the src value

(html/deftemplate template-about "../resources/public/build/about/index.html"
[]
[:img] (html/set-attr :src (str "path1" (urly/path-of ("the src value")))
)

Solution

  • You're looking for an update-attr function, was discussed before

    As in:

    (html/deftemplate template-about "../resources/public/build/about/index.html"
    []
    [:img] (fn [node]
              (let [href (-> node :attrs :href)]
                 (assoc-in node [:attrs :href] (urly/path-of href))))
    

    Or taking the generic path

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

    and then

    (update-attr :href urly/path-of)